leetcode:1154. 一年中的第几天

题目

给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。

示例:

  1. 输入:date = "2019-01-09"
  2. 输出:9
  3. 解释:给定日期是2019年的第九天。
  1. 输入:date = "2019-02-10"
  2. 输出:41

解答 & 代码

  1. class Solution {
  2. public:
  3. int dayOfYear(string date) {
  4. int year = stoi(date.substr(0, 4));
  5. int month = stoi(date.substr(5, 2));
  6. int day = stoi(date.substr(8, 2));
  7. // 每个月的天数
  8. vector<int> monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  9. // 如果是闰年,则二月天数为 29 天
  10. // 闰年:1)普通闰年:年份是 4 的倍数且不是 100 的倍数;2)实际闰年:年份是 400 的倍数
  11. if((year % 100 != 0 && year % 4 == 0) || year % 400 == 0)
  12. monthDays[1] = 29;
  13. // 计算是一年中的第几天
  14. int result = 0;
  15. for(int i = 0; i < month - 1; ++i)
  16. result += monthDays[i];
  17. result += day;
  18. return result;
  19. }
  20. };

复杂度分析:

  • 时间复杂度 O(1):日期字符串长度和一年的月份数都是常数
  • 空间复杂度 O(1):

执行结果:

  1. 执行结果:通过
  2. 执行用时:24 ms, 在所有 C++ 提交中击败了 21.72% 的用户
  3. 内存消耗:6.8 MB, 在所有 C++ 提交中击败了 13.29% 的用户