每日一题-一年中的第几天(简单)

909 阅读2分钟

题目描述:

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

通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。

示例:

示例 1:

输入: date = "2019-01-09"
输出: 9

示例 2:

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

示例 3:

输入: date = "2003-03-01"
输出: 60

示例 4:

输入: date = "2004-03-01"
输出: 61

提示:

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

分析:

题目简单明了,直接计算:从 date 中直接提取相应的year、month、day,一年中第几天即该月份前所有天数之和加上day即可。若是闰年,则二月份多出一天,所以month > 2,则需加一天。 对应每月天数如下:
int[] amount = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};

  • 时间复杂度:O(1)。我们将字符串的长度(定值 7)以及一年的月份数 12 视为常数。

编码:

public int dayOfYear(String date) {
    int[] amount = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
    String[] dateSplit = date.split("-");
    int year = Integer.parseInt(dateSplit[0]);
    int month = Integer.parseInt(dateSplit[1]);
    int day = Integer.parseInt(dateSplit[2]);
    int ans = 0;

    if ((year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) && month > 2){
        ans++;
    }

    ans += amount[month - 1] + day;
    return ans;
}
//大佬的写法:
public int dayOfYear1(String date) {
    int num = 0;
    int year = (date.charAt(0) - '0')*1000 + (date.charAt(1) - '0')*100 + (date.charAt(2) - '0')*10 + (date.charAt(3) - '0');
    int month = (date.charAt(5) - '0')*10 + (date.charAt(6) - '0');
    int day = (date.charAt(8) - '0')*10 + (date.charAt(9) - '0');
    int[] pYear = {0,31,28,31,30,31,30,31,31,30,31,30};
    int[] rYear = {0,31,29,31,30,31,30,31,31,30,31,30};
    if(year % 400 == 0  || (year % 4== 0 && year / 100 != 0)){
        for(int i = 0; i < month; i++)
            num += rYear[i];
    }else{
        for(int i = 0; i < month;i++)
            num += pYear[i];
    }
    return num + day;
}

题目链接