1154. 一年中的第几天
1154. 一年中的第几天
题目
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
Example 1:
Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2:
Input: date = "2019-02-10"
Output: 41
Constraints:
date.length == 10date[4] == date[7] == '-', and all otherdate[i]'s are digitsdaterepresents a calendar date between Jan 1st, 1900 and Dec 31th, 2019.
题目大意
给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。
示例 1:
输入: date = "2019-01-09"
输出: 9
解释: 给定日期是 2019 年的第九天。
示例 2:
输入: date = "2019-02-10"
输出: 41
提示:
date.length == 10date[4] == date[7] == '-',其他的date[i]都是数字date表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日
解题思路
提取年份、月份和日期
从输入的字符串date中提取出年份、月份和日期。判断是否是闰年
由于闰年 2 月有 29 天,需要根据年份判断该年是否为闰年:- 闰年的判断规则是:如果年份能被 4 整除且不能被 100 整除,或者能被 400 整除,则是闰年。
计算从 1 月 1 日到给定日期的天数
我们可以通过一个数组存储每个月的天数,普通年份中:- 1 月:31 天
- 2 月:28 天
- 3 月:31 天
- 4 月:30 天
- ...
如果是闰年,那么 2 月就有 29 天。
累加从 1 月 1 日到给定日期的天数
从 1 月到前一个月的天数之和再加上当前月的天数,即可得到给定日期是当年的第几天。
复杂度分析
- 时间复杂度:
O(1)- 字符串拆分和映射操作是
O(1)的操作。 - 累加天数部分的时间复杂度是
O(1),因为数组长度是固定的(12 个月)。
- 字符串拆分和映射操作是
- 空间复杂度:
O(1),使用了一个常量大小的数组daysInMonth。
代码
/**
* @param {string} date
* @return {number}
*/
var dayOfYear = function (date) {
const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // 普通年份的每月天数
// 提取年份、月份和日期
const [year, month, day] = date.split('-').map(Number);
// 判断是否是闰年
const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
// 如果是闰年,2月的天数为29天
if (isLeapYear) {
daysInMonth[1] = 29;
}
// 计算从1月1日到给定日期的天数
let days = 0;
for (let i = 0; i < month - 1; i++) {
days += daysInMonth[i];
}
days += day; // 加上当前月的天数
return days;
};
