LeetCode 题解工作台

一周中的第几天

给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。 输入为三个整数: day 、 month 和 year ,分别表示日、月、年。 您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Fri…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们可以使用蔡勒公式来计算星期几,蔡勒公式如下: $$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。

输入为三个整数:daymonth 和 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 年之间的有效日期。
lightbulb

解题思路

方法一:蔡勒公式

我们可以使用蔡勒公式来计算星期几,蔡勒公式如下:

w=(c42c+y+y4+13(m+1)5+d1)mod7w = (\left \lfloor \frac{c}{4} \right \rfloor - 2c + y + \left \lfloor \frac{y}{4} \right \rfloor + \left \lfloor \frac{13(m+1)}{5} \right \rfloor + d - 1) \bmod 7

其中:

  • w: 星期(从 Sunday 开始)
  • c: 年份前两位
  • y: 年份后两位
  • m: 月(m 的取值范围是 3 至 14,即在蔡勒公式中,某年的 1、2 月要看作上一年的 13、14 月来计算,比如 2003 年 1 月 1 日要看作 2002 年的 13 月 1 日来计算)
  • d: 日
  • ⌊⌋: 向下取整
  • mod: 取余

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        return datetime.date(year, month, day).strftime('%A')
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

一周中的第几天题解:数学·driven | LeetCode #1185 简单