LeetCode 题解工作台

一年中的第几天

给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。 示例 1: 输入: date = "2019-01-09" 输出: 9 解释: 给定日期是2019年的第九天。 示例 2: 输入: date = "2019-02-10" 输出: 4…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·string

bolt

答案摘要

根据题意,给定的日期是公元纪年法的日期,因此可以直接计算出该日期是当年的第几天。 首先,根据给定的日期计算出年月日,分别为 , , 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。

 

示例 1:

输入:date = "2019-01-09"
输出:9
解释:给定日期是2019年的第九天。

示例 2:

输入:date = "2019-02-10"
输出:41

 

提示:

  • date.length == 10
  • date[4] == date[7] == '-',其他的 date[i] 都是数字
  • date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日
lightbulb

解题思路

方法一:直接计算

根据题意,给定的日期是公元纪年法的日期,因此可以直接计算出该日期是当年的第几天。

首先,根据给定的日期计算出年月日,分别为 yy, mm, dd

然后,根据公元纪年法的闰年规则,计算出当年二月份的天数,闰年的二月份有 2929 天,平年的二月份有 2828 天。

闰年的计算规则是:年份能被 400400 整除,或者年份能被 44 整除且不能被 100100 整除。

最后,根据给定的日期计算出当年的第几天,即把前面每个月的天数累加起来,再加上当月的天数即可。

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

1
2
3
4
5
6
7
class Solution:
    def dayOfYear(self, date: str) -> int:
        y, m, d = (int(s) for s in date.split('-'))
        v = 29 if y % 400 == 0 or (y % 4 == 0 and y % 100) else 28
        days = [31, v, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        return sum(days[: m - 1]) + d
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Look for candidates who correctly handle leap years using conditional checks.

  • question_mark

    Evaluate understanding of how arrays can optimize counting days across months.

  • question_mark

    Ensure that candidates can break down the problem into small, manageable steps.

warning

常见陷阱

外企场景
  • error

    Forgetting to account for leap years, which can cause an off-by-one error in February.

  • error

    Incorrectly indexing the month, as arrays in programming are often zero-indexed, but months are one-indexed in this problem.

  • error

    Not handling edge cases, such as dates in December or the very start of the year.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling different date formats, such as MM-DD-YYYY.

  • arrow_right_alt

    Calculating the day number for a different range of years, not limited to 1900–2019.

  • arrow_right_alt

    Optimizing the approach for larger datasets or multiple date calculations in one go.

help

常见问题

外企场景

一年中的第几天题解:数学·string | LeetCode #1154 简单