多时段时间校验时间是否重叠(交集)

时间冲突算法

入参:

Date startTime:开始时间

Date endTime:结束时间

List<Pair<Date,Date>> timePairs:时间段列表

出参:

boolean b:true:会发生时间重合,false:不会发生时间重合

算法简介:

将 从startTime到endTime的时间段 插入到 timePairs这个时间段列表中,校验是否会发生冲突。

代码

public static boolean validateDurationConflict(Date startTime, Date endTime, List<Pair<Date,Date>> timePairs){
        if(startTime == null || endTime == null || timePairs == null){
            throw new IllegalArgumentException("startTime is null or endTime is null or timePairs is empty when validateDurationConflict !");
        }
 
        //过滤null
        //排序:按时间片中的开始时间进行从小到大排序
        timePairs = timePairs.stream()
                .filter(pair -> pair != null && pair.getKey() != null && pair.getValue() != null)
                .sorted(Comparator.comparing(Pair::getKey)).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(timePairs)){
            throw new IllegalArgumentException("timePairs is empty or its element is null when cutDurationIntoTimePairs !");
        }
        
        //校验 timePairs 各个时间片之间不能有重合
        Pair<Date, Date> pPair = null;
        for(int i = 0; i < timePairs.size(); i++){
            Pair<Date, Date> pair = timePairs.get(i);
            Date sTime = pair.getKey();
            Date eTime = pair.getValue();
            if(i == 0){
                pPair = pair;
                continue;
            }
            if(pPair.getValue().compareTo(sTime) > 0){
                throw new IllegalArgumentException("timePairs has time coincide when cutDurationIntoTimePairs !");
            }
            pPair = pair;
        }
        
        //获取第一个开始时间大于startTime的那个时间段的下标
        int index = 0;
        for(int i=0; i<timePairs.size(); i++){
            Pair<Date,Date> timePair = timePairs.get(i);
            if(i == 0 && endTime.compareTo(timePair.getKey()) < 0){
                return false;
            }
            if(i == timePairs.size()-1 && startTime.compareTo(timePair.getValue()) > 0){
                return false;
            }
            if(startTime.compareTo(timePair.getKey()) < 0){
                index = i;
                break;
            }
        }
        if(index > 0){
            Pair<Date,Date> firstTimePair = timePairs.get(index-1);
            Pair<Date,Date> secondTimePair = timePairs.get(index);
            if(startTime.compareTo(firstTimePair.getValue()) > 0
                    && endTime.compareTo(secondTimePair.getKey()) < 0){
                return false;
            }
        }
        return true;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值