interval [startTime, st
opt
ime) ----integral time stamps
给这样的一串区间 I1, I2......In
找出 一个 time stamp 出现在interval的次数最多。
startTime <= t< stopTime 代表这个数在区间里面出现过。 . 鐗涗汉浜戦泦,涓€浜╀笁鍒嗗湴
. more info on 1point3acres.com
example: [1,3), [2, 7), [4, 8), [5, 9)
给这样的一串区间 I1, I2......In
找出 一个 time stamp 出现在interval的次数最多。
startTime <= t< stopTime 代表这个数在区间里面出现过。 . 鐗涗汉浜戦泦,涓€浜╀笁鍒嗗湴
. more info on 1point3acres.com
example: [1,3), [2, 7), [4, 8), [5, 9)
5和6各出现了三次, 所以答案返回5,6
这个最大interval必定是某个区间的头到某个区间的尾
public static void main(String[] args) {
IntervalIntersection s = new IntervalIntersection();
System.out.println(s.find(new int[][] { { 1, 3 }, { 2, 7 }, { 4, 8 }, { 5, 9 } }));
System.out.println(s.find(new int[][] { { 1, 10 } }));
System.out.println(s.find(new int[][] { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 },
{ 6, 7 }, { 7, 8 }, { 8, 9 } }));
System.out.println(s.find(new int[][] { { 1, 2 } }));
System.out.println(s.find(new int[][] { { 5, 9 }, { 5, 10 }, { 7, 13 } }));
System.out.println(s.find(new int[][] {}));
System.out.println(s.find(new int[][] { { 1, 4 }, { 1, 4 }, { 1, 4 } }));
}
class TimePoint {
int time;
boolean isStart;
public TimePoint(int time, boolean isStart) {
this.time = time;
this.isStart = isStart;
}
}
public List<Integer> find(int[][] intervals) {
List<TimePoint> timePoints = new ArrayList<>();
for (int[] interval: intervals) {
timePoints.add(new TimePoint(interval[0], true));
timePoints.add(new TimePoint(interval[1], false));
}
Collections.sort(timePoints, new Comparator<TimePoint>(){
@Override
public int compare(TimePoint a, TimePoint b){
if (a.time != b.time) {
return a.time - b.time;
} else {
if (a.isStart || !b.isStart) {
return -1;
} else {
return 1;
}
}
}
});
List<Integer> list = new LinkedList<>();
int count = 0,/*count of start*/ max = 0;//max intersections
for (TimePoint tp: timePoints) {
if (tp.isStart) {
count++;
if (count > max) {
list.clear();
list.add(tp.time);
max = count;
} else if (count == max) {
list.add(tp.time);
}
} else {
if (count == max) {
list.add(tp.time);
}
count--;
}
}
List<Integer> res = new LinkedList<>();
for (int i = 0; i < list.size() - 1; i = i + 2) {
for (int j = list.get(i); j < list.get(i + 1); j++) {
res.add(j);
}
}
return res;
}