来自北大算法课的Leetcode题解:1154. 一年中的第几天

本题代码https://github.com/doubleZ0108/Leetcode/blob/master/1154.%E4%B8%80%E5%B9%B4%E4%B8%AD%E7%9A%84%E7%AC%AC%E5%87%A0%E5%A4%A9.py

  • 解法1(T5% S41%):直接调用库函数将元旦和当前时间都转换为Date类型的变量,然后直接相减计算时间差
    • datetime.datetime.strptime(date, "%Y-%m-%d").date():将字符串变为Date变量
  • 解法2(T71% S44%):标准解法,首先把字符串分割成年月日,然后判断是否为闰年,并设立每个月有几天的数组,最后累加一下之前月的总天数再加上这个月过的天数
    • 闰年:(整除4 & 不能整除100) | (整除400)
class Solution(object):
    def dayOfYear(self, date):
        """
        :type date: str
        :rtype: int
        """
        # 解法1
        date_ = date[:4] + "-01-01"
        date1 = datetime.datetime.strptime(date, "%Y-%m-%d").date()
        date2 = datetime.datetime.strptime(date_, "%Y-%m-%d").date()
        return (date1-date2).days + 1

    def otherSolution(self, date):
        # 解法2
        def isLeap(year):
            return (year%4==0 and year%100!=0) or (year % 400 == 0)

        year, month, day = tuple(map(lambda x: int(x), date.split('-')))
        days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if isLeap(year):
            days_of_month[2-1] += 1
        
        res = 0
        for i in range(month-1):
            res += days_of_month[i]
        return res + day 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

doubleZ0108

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值