前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >脚撕LeetCode(1154)Easy

脚撕LeetCode(1154)Easy

作者头像
JathonKatu
发布2022-01-18 08:14:33
1660
发布2022-01-18 08:14:33
举报
文章被收录于专栏:JathonKatu

题目地址:https://leetcode-cn.com/problems/day-of-the-year/

给你一个按 YYYY-MM-DD 格式表示日期的字符串date,请你计算并返回该日期是当年的第几天。 通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。 每个月的天数与现行公元纪年法(格里高利历)一致。

代码语言:javascript
复制
示例 1: 
输入:date = "2019-01-09" 
输出:9
示例 2: 
输入:date = "2019-02-10" 
输出:41

https://leetcode-cn.com/problems/day-of-the-year/

代码语言:javascript
复制
示例 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 日。

https://leetcode-cn.com/problems/day-of-the-year/

这道题的题意就是,给你一个年月日,返回这一天是当年的第几天。

首先要明确的是,当前月份之前的所有月份日都要加上,然后在加上给的日即可,这里引出一个问题,就是前面所有月份中,二月份又可能碰上闰年就会+1,所以还要对是否闰年进行判断

一、爆破法:

我们提供的数组,是当前月份-1作为下标去数组中获取的这个月之前的天数。

闰年的计算方式是,必须能整除4,且整除100的不算,但整除400的算。

执行结果如下:

10957 / 10957 个通过测试用例

状态:通过

执行用时: 11 ms

内存消耗: 38.9 MB

代码语言:javascript
复制
public static final int[] monthArr = {0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};

public static int dayOfYearMe(String date) {
    int ans = 0;
    int month = Integer.parseInt(date.substring(5, 7));
    ans = monthArr[month-1];
    if (2 < month) {
        ans += isLeapYear(date) ? 1 : 0;
    }
    return ans += Integer.parseInt(date.substring(8));
}

public static boolean isLeapYear(String date) {
    int year = Integer.parseInt(date.substring(0,4));
    return (year & 3) == 0 && (year % 100 != 0 || year % 400 == 0);
}

二、爆破法二

方法2在方法一基础上,修改了一些细节,差别不大

执行结果如下:

10957 / 10957 个通过测试用例

状态:通过

执行用时: 10 ms

内存消耗: 39 MB

代码语言:javascript
复制
public static int dayOfYearMe2(String date) {
    int ans = 0;
    int year = Integer.parseInt(date.substring(0,4));
    int month = Integer.parseInt(date.substring(5,7));
    int day = Integer.parseInt(date.substring(8));
    int[] monthArr = {0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    ans = monthArr[month-1];
    ans += day;
    if (month > 2 && ( year % 400 == 0 || ((year & 3) == 0 && year % 100 != 0))) {
        ans += 1;
    }
    return ans;
}

我的答案得分很低,我尝试运行评论区中双百大佬的答案也和我差不多,而且内存和时间也没有他们截图的那么小。所以这道题找了半天都没有接近双百的,就这样搁置了(总感觉是力扣出了问题hhhhh)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-06-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 JathonKatu 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档