2409. 统计共同度过的日子数 - Java 模拟

Smile_slime_47

原题地址:https://leetcode.cn/problems/count-days-spent-together/

题解

通过一个函数dateToIndexMM-DD格式的日期转换为一年中的第N天,这样我们就能得到Alice和Bob的来往日期在一年中的子区间

如第一个实例中就是:

  • Alice:[227,230]
  • Bob:[228,231]

对于两个子区间求交集有一套共通的办法:

  • 若子区间A的两个边界均大于B的右边界或均小于B的左边界,则A和B无交集
  • 此外有A和B的交集:A和B的右边界的较小值减去A和B的左边界的较大值

时间复杂度:O(N)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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) {
int[] alice=new int[2];
int[] bob=new int[2];
alice[0]=dateToIndex(arriveAlice);
alice[1]=dateToIndex(leaveAlice);
bob[0]=dateToIndex(arriveBob);
bob[1]=dateToIndex(leaveBob);

if((alice[0]<bob[0]&&alice[1]<bob[0])||(alice[0]>bob[1]&&alice[1]>bob[1])){
return 0;
}else{
return Math.min(alice[1],bob[1])-Math.max(alice[0],bob[0])+1;
}
}

int dateToIndex(String dateStr){
int[] date=new int[2];
date[0]=(dateStr.charAt(0)-'0')*10+(dateStr.charAt(1)-'0');
date[1]=(dateStr.charAt(3)-'0')*10+(dateStr.charAt(4)-'0');
int ret=0;
for(int i=0;i<date[0]-1;i++){ret+=days[i];}
ret+=date[1];
return ret;
}
}
Comments
On this page
2409. 统计共同度过的日子数 - Java 模拟