forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path435-Non-Overlapping-Intervals.java
More file actions
35 lines (30 loc) · 1.01 KB
/
435-Non-Overlapping-Intervals.java
File metadata and controls
35 lines (30 loc) · 1.01 KB
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
public class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
int intervalsRemoved = 0;
Arrays.sort(
intervals,
(arr1, arr2) -> Integer.compare(arr1[0], arr2[0])
);
int[] intervalFirst = intervals[0];
for (int i = 1; i < intervals.length; i++) {
if (firstIntervalwithinSecond(intervalFirst, intervals[i])) {
//mark first interval to be removed
intervalsRemoved++;
// determine which interval to remove
//remove the interval that ends last
if (intervalFirst[1] > intervals[i][1]) {
intervalFirst = intervals[i];
}
} else {
intervalFirst = intervals[i];
}
}
return intervalsRemoved;
}
public boolean firstIntervalwithinSecond(
int[] intervalFirst,
int[] intervalSecond
) {
return intervalSecond[0] < intervalFirst[1];
}
}