leetcode 1185. Day of the Week(python)

291 阅读1分钟

描述

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the day, month and year respectively.

Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.

Example 1:

Input: day = 31, month = 8, year = 2019
Output: "Saturday"	

Example 2:

Input: day = 18, month = 7, year = 1999
Output: "Sunday"

Example 3:

Input: day = 15, month = 8, year = 1993
Output: "Sunday"

Note:

The given dates are valid dates between the years 1971 and 2100.

解析

根据题意,就是计算某一天是星期几,我这里先找到了 1970 年第一天是星期四,然后算出某一天距离这一天相差的天数,通过 l[(days - 1 + 4) % 7] 就可以知道是星期几。

解答

class Solution(object):
    def dayOfTheWeek(self, day, month, year):
        """
        :type day: int
        :type month: int
        :type year: int
        :rtype: str
        """
        # (1,1,1970)  Thursday
        l = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
        def isRun(year):
            if (year % 4) == 0:
                if (year % 100) == 0:
                    if (year % 400) == 0:
                        return True
                    else:
                        return False
                else:
                    return True
            else:
                return False

        d = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,
             7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
        if isRun(year):
            d[2] = 29
        days = 0
        for y in range(1970, year):
            if isRun(y):
                days += 366
            else:
                days += 365
        for m in range(1, month):
            days += d[m]
        days += day
        return l[(days - 1 + 4) % 7]            	      
		

运行结果

Runtime: 16 ms, faster than 72.50% of Python online submissions for Day of the Week.
Memory Usage: 13.3 MB, less than 93.33% of Python online submissions for Day of the Week.

原题链接:leetcode.com/problems/da…

您的支持是我最大的动力