给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入为三个整数:
day
、month
?和?year
,分别表示日、月、年。您返回的结果必须是这几个值中的一个?
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
。
?
class Solution {
public:
string dayOfTheWeek(int day, int month, int year) {
}
};
今天出这个题莫名其妙的,我们只需要找一天为基准,算出距离基准日期的天数,就能得到第几周了。根据数据范围是1971到2100之间,那么我们以1970.12.31为基准,算偏移了几天就行
或者我们也可以直接调用库函数,这也是工程中常用做法
时间复杂度:O(C) 空间复杂度:O(C)
?手写版
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"};
库函数版
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")