题目:2409.统计共同度过的日子数

题目来源:

        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;
    }
}
 

总结:

        脑子一抽在三目元素赋结果里面加了个三目运算符,导致代码巨难看。

        官方题解将日期转化为一年中的第几天在计算差值。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值