Java判断多个时间段是否重叠(重叠区间个数)
import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 判断多个时间段是否出现重叠 * @author cavancao */ public class TimeSlotUtil { public static boolean checkOverlap(List<String> list){ Collections.sort(list);//排序ASC boolean flag = false;//是否重叠标识 for(int i=0; i<list.size(); i++){ if(i>0){ //跳过第一个时间段不做判断 String[] itime = list.get(i).split("-"); for(int j=0; j<list.size(); j++){ //如果当前遍历的i开始时间小于j中某个时间段的结束时间那么则有重叠,反之没有重叠 //这里比较时需要排除i本身以及i之后的时间段,因为已经排序了所以只比较自己之前(不包括自己)的时间段 if(j==i || j>i){ continue; } String[] jtime = list.get(j).split("-"); //此处DateUtils.compare为日期比较(返回负数date1小、返回0两数相等、返回正整数date1大) int compare = DateUtils.compare( (DateUtils.getDate()+" "+itime[0]+":00"), (DateUtils.getDate()+" "+jtime[1]+":00"), "yyyy-MM-dd HH:mm:ss"); if(compare<0){ flag = true; break;//只要存在一个重叠则可退出内循环 } } } //当标识已经认为重叠了则可退出外循环 if(flag){ break; } } return flag; } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("08:00-09:00"); list.add("09:00-12:00"); list.add("13:00-16:30"); list.add("16:00-17:00"); list.add("18:00-20:00"); boolean flag = checkOverlap(list); for(String time : list){ System.out.println(time); } System.out.println("\n当前时间段列表重叠验证结果为:" + flag); } }
/* * TimeSlotUtil.java * Version 1.0.0 * Created on 2017年12月1日 * Copyright ReYo.Cn */ package reyo.sdk.utils.test.dy; import java.util.Arrays; /** * 判断多个时间段是否出现重叠 * @author cavancao */ class Interval { int start; //起点 int end; //终点 Interval(int a, int b) { start = a; end = b; } } class Point implements Comparable<Point> { int value; //数值 int type; //点的类型,0为起点,1为终点 Point(int v, int t) { value = v; type = t; } //实现compareTo函数 @Override public int compareTo(Point p) { if (this.value == p.value) { return 0; } else if (this.value > p.value) { return 1; } else { return -1; } } //区间转换 } public class TimeSlotUtil2 { public int getOverlappingCount(Interval[] A) { int max = 0, count = 1; if (A == null || A.length == 0) return max; Point[] points = new Point[A.length * 2]; for (int i = 0; i < A.length; i++) { points[2 * i] = new Point(A[i].start, 0); points[2 * i + 1] = new Point(A[i].end, 1); } //Collection.sort(points); Arrays.sort(points); for (int i = 0; i < points.length; i++) { if (points[i].type == 0) { count++; max = Math.max(max, count); } else { count--; } } return max; } public static void main(String[] args) { Interval[] testInterval = new Interval[4]; testInterval[0] = new Interval(1, 5); testInterval[1] = new Interval(10, 15); testInterval[2] = new Interval(5, 10); testInterval[3] = new Interval(20, 30); TimeSlotUtil2 demo = new TimeSlotUtil2(); int max = demo.getOverlappingCount(testInterval); System.out.println(max); } }