侧边栏壁纸
博主头像
GabrielxD

列車は必ず次の駅へ。では舞台は?私たちは?

  • 累计撰写 674 篇文章
  • 累计创建 128 个标签
  • 累计收到 20 条评论

目 录CONTENT

文章目录

【模拟】统计共同度过的日子数【力扣第 87 场双周赛】

GabrielxD
2022-09-18 / 0 评论 / 0 点赞 / 117 阅读 / 567 字
温馨提示:
本文最后更新于 2022-09-18,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

题目

6184. 统计共同度过的日子数


Alice 和 Bob 计划分别去罗马开会。

给你四个字符串 arriveAlice ,leaveAlice ,arriveBob 和 leaveBob 。Alice 会在日期 arriveAlice 到 leaveAlice 之间在城市里(日期为闭区间),而 Bob 在日期 arriveBob 到 leaveBob 之间在城市里(日期为闭区间)。每个字符串都包含 5 个字符,格式为 "MM-DD" ,对应着一个日期的月和日。

请你返回 Alice 和 Bob 同时在罗马的天数。

你可以假设所有日期都在 同一个 自然年,而且 不是 闰年。每个月份的天数分别为:[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 。

示例 1:

输入:arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"
输出:3
解释:Alice 从 8 月 15 号到 8 月 18 号在罗马。Bob 从 8 月 16 号到 8 月 19 号在罗马,他们同时在罗马的日期为 8 月 16、17 和 18 号。所以答案为 3 。

示例 2:

输入:arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31"
输出:0
解释:Alice 和 Bob 没有同时在罗马的日子,所以我们返回 0 。

提示:

  • 所有日期的格式均为 "MM-DD" 。
  • Alice 和 Bob 的到达日期都 早于或等于 他们的离开日期。
  • 题目测试用例所给出的日期均为 非闰年 的有效日期。

解题

方法一:模拟

思路

直接根据题意模拟即可,注意日期的处理。

代码

class Solution {
    static final int[] DATE = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    
    public int countDaysTogether(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob) {
        int[] counts = new int[366];
        int arriveAliceMonth = Integer.parseInt(arriveAlice.substring(0, 2));
        int startA = DATE[arriveAliceMonth - 1] + Integer.parseInt(arriveAlice.substring(3, 5)) - 1;
        int leaveAliceMonth = Integer.parseInt(leaveAlice.substring(0, 2));
        int endA = DATE[leaveAliceMonth - 1] + Integer.parseInt(leaveAlice.substring(3, 5)) - 1;
        for (int i = startA; i <= endA; ++i) ++counts[i];
        int arriveBobMonth = Integer.parseInt(arriveBob.substring(0, 2));
        int startB = DATE[arriveBobMonth - 1] + Integer.parseInt(arriveBob.substring(3, 5)) - 1;
        int leaveBobMonth = Integer.parseInt(leaveBob.substring(0, 2));
        int endB = DATE[leaveBobMonth - 1] + Integer.parseInt(leaveBob.substring(3, 5)) - 1;
        int ans = 0;
        for (int i = startB; i <= endB; ++i) {
            if (counts[i] == 1) ++ans;
        }
        return ans;
    }
}
0

评论区