力扣2409统计共同度过的日子数
Alice
和Bob
计划分别去罗马开会。
给你四个字符串arriveAlice
,leaveAlice
,arriveBob
和leaveBob
。Alice
会在日期arriveAlice
到leaveAlice
之间在城市里(日期为闭区间),而Bob
在日期arriveBob
到leaveBob
之间在城市里(日期为闭区间)。每个字符串都包含 5 5 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 。
class Solution {
int[] days = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public int countDaysTogether(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob) {
String[] aa = arriveAlice.split("\\-"), la = leaveAlice.split("\\-");
String[] ab = arriveBob.split("\\-"), lb = leaveBob.split("\\-");
int a = Integer.valueOf(aa[0]), b = Integer.valueOf(aa[1]);
int c = Integer.valueOf(la[0]), d = Integer.valueOf(la[1]);
int e = Integer.valueOf(ab[0]), f = Integer.valueOf(ab[1]);
int g = Integer.valueOf(lb[0]), h = Integer.valueOf(lb[1]);
// 转化为一年的第几天
int aliceArriveTime = time(a - 1) + b, aliceLeaveTime = time(c - 1) + d;
int bobArriveTime = time(e - 1) + f, bobLeaveTime = time(g - 1) + h;
//判断是否有交集
if (bobLeaveTime >= aliceArriveTime && aliceLeaveTime >= bobArriveTime) {
//存在交集, 那么交集就是一方离开的时间和另一方到达的时间之差 +1
//要 +1是因为:假如 10.30 都同时在,时间相减为 0, 实际相遇时间为 1天
return Math.min(bobLeaveTime, aliceLeaveTime) - Math.max(bobArriveTime, aliceArriveTime) + 1;
}
return 0;
}
public int time(int month) {
int sum = 0;
for (int i = 0; i < month; i++) { sum += days[i]; }
return sum;
}
}
考点: 1. 是否存在交集(一维) 2. 交集的区间长度