建设手机银行网站,做网站难度大吗,萝岗高端网站建设,建筑网片自动清洗机#x1f525;博客主页#xff1a; A_SHOWY#x1f3a5;系列专栏#xff1a;力扣刷题总结录 数据结构 云计算 数字图像处理 力扣每日一题_ 这三天的题目难度相对较小#xff0c;基本都为模拟题#xff0c;但是第二三的题目年份贡献类型很有代表性。2023年最后三天年终收…博客主页 A_SHOWY系列专栏力扣刷题总结录 数据结构 云计算 数字图像处理 力扣每日一题_ 这三天的题目难度相对较小基本都为模拟题但是第二三的题目年份贡献类型很有代表性。2023年最后三天年终收尾正好是周日下次的每日一题更新新的一年新的一周开始。 【12.29】2706.购买两块巧克力
2706. 购买两块巧克力https://leetcode.cn/problems/buy-two-chocolates/ 可以说是睡的最早的一集就是一个排序后一次遍历的问题3分钟秒了 class Solution {
public:int buyChoco(vectorint prices, int money) {sort(prices.begin(),prices.end());int ans 0;for(int i 0 ; i 2;i ){ans prices[i];}if(ans money) return (money - ans);else return money;}
};
【12.30】 1185.一周中的第几天
1185. 一周中的第几天https://leetcode.cn/problems/day-of-the-week/ 虽然是一个简单题但是并不轻松是一道稍微复杂的模拟题目首先要熟悉判断闰年的条件同时考虑清楚年、月、日的贡献和当年如果是闰年需要多共贡献一天。 首先我们应该找到一个 baseline然后将所给的日期基于这个 baseline 计算偏移量。因为题目所给的日期是在 1971 到 2100 年之间的有效日期所以我们可以选取1970年12月31日为baseline这一天是星期四基于这个日期计算偏移量。
class Solution {
public:string dayOfTheWeek(int day, int month, int year) {vectorstring week {Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday};vectorint monthdays {31,28,31,30,31,30,31,31,30,31,30,};//年份的贡献int days 365*(year - 1 - 1970);for(int i 1971; i year;i){if(i % 400 0 || (i % 4 0 i % 100 ! 0)) days 1;}//判断是否闰年if(month 2 (year % 400 0 || (year % 4 0 year % 100 ! 0))) days 1;//月份贡献for(int i 0; i month-1; i){days monthdays[i];}//天贡献days day;return week[(days 3) % 7];}
}; 判断闰年的条件能被400整除或者能被4整除但不能被400整除。
i % 400 0 || (i % 4 0 i % 100 ! 0)
在判断年的贡献的时候year要先减去1因为不算今年的今年的在后月份和天数的时候另算
int days 365*(year - 1 - 1970);
判断完年份以后要判断当年是不是闰年且大于2月份如果是闰年加1最后返回的时候由于1970年12月31日是星期4可以假设1971年1月1日是星期5是days是1对应Tuesday而对应应该是Friday所以加三再除以7取模。 return week[(days 3) % 7];
【12.31】1154.一年中的第几天
1154. 一年中的第几天https://leetcode.cn/problems/day-of-the-year/ 也是模拟题有了前一天的铺垫今天的题目就显得简单的多了也是通过年月日计算但是这道题需要掌握复制子串的语句substr。 class Solution {
public:int dayOfYear(string date) {//复制子串int year stoi(date.substr(0,4));int month stoi(date.substr(5,2));int day stoi(date.substr(8,2));vectorint monthdays {31,28,31,30,31,30,31,31,30,31,30};int days 0;for(int i 0; i month - 1; i){days monthdays[i];}if(year % 400 0 ||(year % 4 0 year % 100 ! 0)){if(month 2) days 1;}days day;return days;}
};
通过复制子串的操作求出年月日 第一个参数表示从几开始第二个参数表示长度 int year stoi(date.substr(0,4));int month stoi(date.substr(5,2));int day stoi(date.substr(8,2));
同样通过求月份贡献判断是否闰年再加上日的贡献返回即可。