LeetCode题解(1154):判断日期在一年中的第几天(Python)
发布日期:2021-06-29 19:55:29 浏览次数:2 分类:技术文章

本文共 990 字,大约阅读时间需要 3 分钟。

题目:(简单)

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( 1 ) O(1) O(1) O ( 1 ) O(1) O(1) 32ms (96.43%)
Ans 2 (Python) O ( 1 ) O(1) O(1) O ( 1 ) O(1) O(1) 40ms (72.62%)
Ans 3 (Python)

LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。

解法一:

def dayOfYear(self, date: str) -> int:    year, month, date = date.split("-")    year, month, date = int(year), int(month), int(date)    leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)    if leap:        month_days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]    else:        month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]    return sum(month_days[:month - 1]) + date

解法二(优雅化):

def dayOfYear(self, date: str) -> int:    year, month, date = map(int, date.split("-"))    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):        month_days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]    else:        month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]    return sum(month_days[:month - 1]) + date

转载地址:https://dataartist.blog.csdn.net/article/details/107107592 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(1160):判断可由指定字母拼写的所有单词总长(Python)
下一篇:LeetCode题解(1137):计算斐波那契数列(Python)

发表评论

最新留言

不错!
[***.144.177.141]2024年04月10日 14时07分45秒