LeetCode 题解工作台
日期之间隔几天
请你编写一个程序来计算两个日期之间隔了多少天。 日期以字符串形式给出,格式为 YYYY-MM-DD ,如示例所示。 示例 1: 输入: date1 = "2019-06-29", date2 = "2019-06-30" 输出: 1 示例 2: 输入: date1 = "2020-01-15", d…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·string
答案摘要
我们先定义一个函数 `isLeapYear(year)` 来判断给定的年份 `year` 是否是闰年,如果是闰年则返回 `true`,否则返回 `false`。 接下来,我们再定义一个函数 `daysInMonth(year, month)` 来计算给定的年份 `year` 和月份 `month` 一共有多少天,我们可以使用一个数组 `days` 来存储每个月份的天数,其中 `days[1]` 表…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。
示例 1:
输入:date1 = "2019-06-29", date2 = "2019-06-30" 输出:1
示例 2:
输入:date1 = "2020-01-15", date2 = "2019-12-31" 输出:15
提示:
- 给定的日期是
1971年到2100年之间的有效日期。
解题思路
方法一:数学
我们先定义一个函数 isLeapYear(year) 来判断给定的年份 year 是否是闰年,如果是闰年则返回 true,否则返回 false。
接下来,我们再定义一个函数 daysInMonth(year, month) 来计算给定的年份 year 和月份 month 一共有多少天,我们可以使用一个数组 days 来存储每个月份的天数,其中 days[1] 表示二月份的天数,如果是闰年则为 天,否则为 天。
然后,我们再定义一个函数 calcDays(date) 来计算给定的日期 date 距离 1971-01-01 有多少天,我们可以使用 date.split("-") 来将日期 date 按照 - 分割成年份 year、月份 month 和日期 day,然后我们可以使用一个循环来计算从 1971 年到 year 年一共有多少天,然后再计算从 1 月到 month 月一共有多少天,最后再加上 day 天即可。
最后,我们只需要返回 calcDays(date1) - calcDays(date2) 的绝对值即可。
时间复杂度 ,其中 表示给定的日期距离 1971-01-01 的年数,而 表示给定的日期的月数。空间复杂度 。
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
def isLeapYear(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def daysInMonth(year: int, month: int) -> int:
days = [
31,
28 + int(isLeapYear(year)),
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
]
return days[month - 1]
def calcDays(date: str) -> int:
year, month, day = map(int, date.split("-"))
days = 0
for y in range(1971, year):
days += 365 + int(isLeapYear(y))
for m in range(1, month):
days += daysInMonth(year, m)
days += day
return days
return abs(calcDays(date1) - calcDays(date2))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) because date calculations involve fixed-size arithmetic regardless of input. Space complexity is O(1) as only constant variables and arrays for month lengths are used. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect clear handling of string parsing and date conversion logic.
- question_mark
Look for awareness of leap years and month-specific day counts.
- question_mark
Check for simplicity in computing total days without iterative counting from one date to another.
常见陷阱
外企场景- error
Ignoring leap years and producing off-by-one errors for February dates.
- error
Swapping date1 and date2 incorrectly or not taking absolute difference.
- error
Assuming all months have 30 or 31 days instead of using correct month lengths.
进阶变体
外企场景- arrow_right_alt
Calculate business days only between two dates, skipping weekends.
- arrow_right_alt
Include time in hours and minutes to compute the difference precisely.
- arrow_right_alt
Determine the day of the week for each date in addition to the difference.