LeetCode 题解工作台
一周中的第几天
给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。 输入为三个整数: day 、 month 和 year ,分别表示日、月、年。 您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Fri…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们可以使用蔡勒公式来计算星期几,蔡勒公式如下: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入为三个整数:day、month 和 year,分别表示日、月、年。
您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}。
注意:1971 年 1 月 1 日是星期五。
示例 1:
输入:day = 31, month = 8, year = 2019 输出:"Saturday"
示例 2:
输入:day = 18, month = 7, year = 1999 输出:"Sunday"
示例 3:
输入:day = 15, month = 8, year = 1993 输出:"Sunday"
提示:
- 给出的日期一定是在
1971到2100年之间的有效日期。
解题思路
方法一:蔡勒公式
我们可以使用蔡勒公式来计算星期几,蔡勒公式如下:
其中:
w: 星期(从 Sunday 开始)c: 年份前两位y: 年份后两位m: 月(m 的取值范围是 3 至 14,即在蔡勒公式中,某年的 1、2 月要看作上一年的 13、14 月来计算,比如 2003 年 1 月 1 日要看作 2002 年的 13 月 1 日来计算)d: 日⌊⌋: 向下取整mod: 取余
时间复杂度 ,空间复杂度 。
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
return datetime.date(year, month, day).strftime('%A')
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates a clear understanding of modular arithmetic and its application in date calculations.
- question_mark
The candidate correctly handles edge cases such as leap years and month boundaries.
- question_mark
The candidate exhibits a solid grasp of mathematical patterns involved in calculating days of the week.
常见陷阱
外企场景- error
Forgetting to account for leap years, which may lead to incorrect weekday results for dates in February.
- error
Incorrectly handling months for January and February when applying Zeller's Congruence, which adjusts the month by subtracting 1.
- error
Overcomplicating the solution by introducing unnecessary loops or data structures when a constant time solution is possible.
进阶变体
外企场景- arrow_right_alt
Given a different date format, such as a string, adapt the solution to parse the input correctly before applying the same approach.
- arrow_right_alt
Solve the problem without using Zeller's Congruence by calculating the days in a more manual way.
- arrow_right_alt
Change the range of valid dates, for example from 1900 to 2050, and adjust the solution to handle that new range.