-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindRightInterval.java
85 lines (72 loc) · 3.15 KB
/
FindRightInterval.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public class Solution {
public int[] findRightInterval(Interval[] intervals) { //TLE one easy improvement to to use binary search here binary search is a good friend of sort.
HashMap<Interval, Integer> index = new HashMap<Interval,Integer>();
if(intervals == null || intervals.length<=1){
return new int[]{-1};
}
int[] res = new int[intervals.length];
//List<Interval> endInsrc = new LinkedList<Interval>();
List<Interval> startInsrc = new LinkedList<Interval>();
for(int i=0; i<intervals.length;i++){
index.put(intervals[i],i);
startInsrc.add(intervals[i]);
}
Collections.sort(startInsrc,(a,b)->a.start-b.start);
for(int i=0;i<intervals.length;i++){
Interval cur = intervals[i];
Interval minRight = null;
for(int j=0;j<startInsrc.size();j++){
if(startInsrc.get(j).start>=cur.end){
minRight = startInsrc.get(j);
break;
}
}
if(minRight == null) res[i] = -1;
else res[i] = index.get(minRight);
}
return res;
}
public int[] findRightInterval2(Interval[] intervals) {
int[] result = new int[intervals.length];
java.util.NavigableMap<Integer, Integer> intervalMap = new TreeMap<>();
for (int i = 0; i < intervals.length; ++i) {
intervalMap.put(intervals[i].start, i);
}
for (int i = 0; i < intervals.length; ++i) {
Map.Entry<Integer, Integer> entry = intervalMap.ceilingEntry(intervals[i].end);
result[i] = (entry != null) ? entry.getValue() : -1;
}
return result;
}
public int[] findRightInterval3(Interval[] intervals) {
int [] answer = new int [intervals.length];
List<int[]> sortedIntervals = new ArrayList<>();
for (int idx = 0; idx < intervals.length; idx ++)
sortedIntervals.add(new int[] { intervals [idx].start, idx });
Collections.sort (sortedIntervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1 [0] - o2 [0];
}
});
for (int idx = 0; idx < intervals.length; idx ++) {
int search = intervals [idx].end;
int low = 0, high = sortedIntervals.size() - 1;
boolean found = false;
int mid = -1;
while (low <= high) {
mid = (low + high) >>> 1;
if (sortedIntervals.get(mid)[0] > search)
high = mid - 1;
else if (sortedIntervals.get(mid)[0] < search)
low = mid + 1;
else {
answer[idx] = sortedIntervals.get(mid)[1];
found = true; break;
}
}
answer[idx] = (!found) ? (low < sortedIntervals.size() && high < sortedIntervals.size() ? sortedIntervals.get(low)[1] : -1) : answer[idx];
}
return answer;
}
}