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