forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNonOverlappingIntervals.java
43 lines (34 loc) · 1.25 KB
/
NonOverlappingIntervals.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
class NonOverlappingIntervals {
public int eraseOverlapIntervals(int[][] intervals) {
Comparator<int[]> sortCompare = new Comparator<int[]>(){
@Override
public int compare(int[] a, int[] b ){
if(a[0]==b[0]){
return a[1] - b[1];
} else{
return a[0] - b[0];
}
}
};
Arrays.sort(intervals, sortCompare);
Stack<Pair<Integer, Integer>> st = new Stack<Pair<Integer, Integer>>();
for(int[] interval: intervals){
if(!st.empty()) {
Pair<Integer, Integer> top = st.peek();
if(top.getValue() > interval[0]){ // Overlapping case
if(top.getValue() > interval[1]){
// ----------------------
//. --------------
st.pop();
st.push(new Pair<>(interval[0], interval[1]));
}
} else{
st.push(new Pair<>(interval[0], interval[1]));
}
} else {
st.push(new Pair<>(interval[0], interval[1]));
}
}
return intervals.length -st.size();
}
}