题目来源:
leetcode题目,网址:2409. 统计共同度过的日子数 - 力扣(LeetCode)
解题思路:
获取二人共同度过的日子的起始值和终止值,计算即可。
起始值为二人到达日子中的较大者,中止值为二人到达日子中的较小者。
解题代码:
class Solution {
static int[] days;
public Solution(){
this.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 res=0;
int[] arriveAliceDate=getDate(arriveAlice);
int[] leaveAliceDate=getDate(leaveAlice);
int[] arriveBobDate=getDate(arriveBob);
int[] leaveBobDate=getDate(leaveBob);
int[] startDate=arriveAliceDate[0]==arriveBobDate[0]?(arriveAliceDate[1]>=arriveBobDate[1]?arriveAliceDate:arriveBobDate):(arriveAliceDate[0]>=arriveBobDate[0]?arriveAliceDate:arriveBobDate);
int[] endDate=leaveBobDate[0]==leaveAliceDate[0]?(leaveAliceDate[1]>=leaveBobDate[1]?leaveBobDate:leaveAliceDate):(leaveAliceDate[0]>=leaveBobDate[0]? leaveBobDate:leaveAliceDate);
if(endDate[0]<startDate[0] || (startDate[0]==endDate[0] && endDate[1]<startDate[1]) ){
return 0;
}
if(startDate[0]==endDate[0]){//开始结束在同一个月
return endDate[1]-startDate[1]+1;
}
for(int i=startDate[0];i<=endDate[0];i++){
if(i==startDate[0]){
res+=this.days[i-1]-startDate[1]+1;
}else if(i==endDate[0]){
res+=endDate[1];
}else {
res+=this.days[i-1];
}
}
return res;
}
public int[] getDate(String date){ //res[0]月份,res[1]日子
int[] res=new int[2];
res[0]=(date.charAt(0)-'0')*10+(date.charAt(1)-'0');
res[1]=(date.charAt(3)-'0')*10+(date.charAt(4)-'0');
return res;
}
}
总结:
脑子一抽在三目元素赋结果里面加了个三目运算符,导致代码巨难看。
官方题解将日期转化为一年中的第几天在计算差值。