forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution4.java
62 lines (51 loc) · 1.8 KB
/
Solution4.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
/// https://leetcode.com/problems/non-overlapping-intervals/description/
/// Author : liuyubobobo
/// Time : 2017-11-19
import java.util.Arrays;
import java.util.Comparator;
/// Greedy Algorithm based on ending point
/// Time Complexity: O(n)
/// Space Complexity: O(n)
public class Solution4 {
// Definition for an interval.
public static class Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
}
public int eraseOverlapIntervals(Interval[] intervals) {
if(intervals.length == 0)
return 0;
Arrays.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if(o1.end != o2.end)
return o1.end - o2.end;
return o1.start - o2.start;
}
});
int res = 1;
int pre = 0;
for(int i = 1 ; i < intervals.length ; i ++)
if(intervals[i].start >= intervals[pre].end){
res ++;
pre = i;
}
return intervals.length - res;
}
public static void main(String[] args) {
Interval[] interval1 = {new Interval(1,2),
new Interval(2,3),
new Interval(3,4),
new Interval(1,3)};
System.out.println((new Solution4()).eraseOverlapIntervals(interval1));
Interval[] interval2 = {new Interval(1,2),
new Interval(1,2),
new Interval(1,2)};
System.out.println((new Solution4()).eraseOverlapIntervals(interval2));
Interval[] interval3 = {new Interval(1,2),
new Interval(2,3)};
System.out.println((new Solution4()).eraseOverlapIntervals(interval3));
}
}