LeetCode 1185. 一周中的第几天

一、题目

1、题目描述

给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。

输入为三个整数:daymonthyear,分别表示日、月、年。

您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

2、接口描述

复制代码
cpp 复制代码
class Solution {
public:
    string dayOfTheWeek(int day, int month, int year) {

    }
};

3、原题链接

1185. 一周中的第几天


二、解题报告

1、思路分析

今天出这个题莫名其妙的,我们只需要找一天为基准,算出距离基准日期的天数,就能得到第几周了。根据数据范围是1971到2100之间,那么我们以1970.12.31为基准,算偏移了几天就行

或者我们也可以直接调用库函数,这也是工程中常用做法

2、复杂度

时间复杂度:O(C) 空间复杂度:O(C)

3、代码详解

复制代码
​手写版
复制代码
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++

cpp 复制代码
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

python 复制代码
class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        return datetime.datetime(year, month, day).strftime("%A")
相关推荐
√尖尖角↑1 小时前
力扣——【1991. 找到数组的中间位置】
算法·蓝桥杯
Allen Wurlitzer1 小时前
算法刷题记录——LeetCode篇(1.8) [第71~80题](持续更新)
算法·leetcode·职场和发展
百锦再3 小时前
五种常用的web加密算法
前端·算法·前端框架·web·加密·机密
碳基学AI4 小时前
北京大学DeepSeek内部研讨系列:AI在新媒体运营中的应用与挑战|122页PPT下载方法
大数据·人工智能·python·算法·ai·新媒体运营·产品运营
独家回忆3644 小时前
每日算法-250410
算法
袖清暮雨4 小时前
Python刷题笔记
笔记·python·算法
Marzlam5 小时前
一文读懂数据结构
数据结构
熬夜造bug5 小时前
LeetCode Hot100 刷题笔记(1)—— 哈希、双指针、滑动窗口
笔记·leetcode·hot100
南玖yy5 小时前
探索 C 语言数据结构:从基础到实践
c语言·开发语言·数据结构
风掣长空5 小时前
八大排序——c++版
数据结构·算法·排序算法