網(wǎng)站開(kāi)發(fā)原則愛(ài)站小工具圣經(jīng)
一、題目
1、題目描述
給你一個(gè)日期,請(qǐng)你設(shè)計(jì)一個(gè)算法來(lái)判斷它是對(duì)應(yīng)一周中的哪一天。
輸入為三個(gè)整數(shù):
day
、month
?和?year
,分別表示日、月、年。您返回的結(jié)果必須是這幾個(gè)值中的一個(gè)?
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
。
2、接口描述
?
class Solution {
public:string dayOfTheWeek(int day, int month, int year) {}
};
3、原題鏈接
1185. 一周中的第幾天
二、解題報(bào)告
1、思路分析
今天出這個(gè)題莫名其妙的,我們只需要找一天為基準(zhǔn),算出距離基準(zhǔn)日期的天數(shù),就能得到第幾周了。根據(jù)數(shù)據(jù)范圍是1971到2100之間,那么我們以1970.12.31為基準(zhǔn),算偏移了幾天就行
或者我們也可以直接調(diào)用庫(kù)函數(shù),這也是工程中常用做法
2、復(fù)雜度
時(shí)間復(fù)雜度:O(C) 空間復(fù)雜度:O(C)
3、代碼詳解
?手寫(xiě)版
class Solution {
public:
static constexpr int days[] = { 0 , 31 , 28 , 31 , 30, 31, 30 , 31, 31 , 30 , 31 , 30 ,31};
static vector<string> week;string dayOfTheWeek(int day, int month, int year) {int s = 365 * (year - 1971) + (year - 1969) / 4;for(int i = 1 ; i < month ; i++)s += days[i];if(((!(year % 4) && year % 100) || year % 400 == 0) && month > 2)s++;s += day;return week[(s + 3) % 7];}
};
vector<string> Solution::week = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
庫(kù)函數(shù)版
C++
class Solution {const string weekdays[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
public:string dayOfTheWeek(int day, int month, int year) {tm dt = {0, 0, 0, day, month - 1, year - 1900};time_t t = mktime(&dt);return weekdays[localtime(&t)->tm_wday];}
};
Python3
class Solution:def dayOfTheWeek(self, day: int, month: int, year: int) -> str:return datetime.datetime(year, month, day).strftime("%A")