Skip to content

Commit 45d9170

Browse files
add a solution for 435
1 parent 9ca9c85 commit 45d9170

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/main/java/com/fishercoder/solutions/_435.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,24 @@ public int eraseOverlapIntervals(int[][] intervals) {
2727
}
2828
}
2929

30+
public static class Solution2 {
31+
/**
32+
* This is sorting my starting time, the key here is that we'll want to update end time when an erasure is needed:
33+
* we use the smaller end time instead of the bigger one which is more likely to overlap with others.
34+
*/
35+
public int eraseOverlapIntervals(int[][] intervals) {
36+
Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
37+
int erasures = 0;
38+
int end = intervals[0][1];
39+
for (int i = 1; i < intervals.length; i++) {
40+
if (intervals[i][0] < end) {
41+
erasures++;
42+
end = Math.min(end, intervals[i][1]);
43+
} else {
44+
end = intervals[i][1];
45+
}
46+
}
47+
return erasures;
48+
}
49+
}
3050
}

src/test/java/com/fishercoder/_435Test.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,26 @@
99

1010
public class _435Test {
1111
private static _435.Solution1 solution1;
12+
private static _435.Solution2 solution2;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _435.Solution1();
17+
solution2 = new _435.Solution2();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
int[][] intervals = CommonUtils.convertLeetCodeIrregularLengths2DArrayInputIntoJavaArray("[1,2],[2,3],[3,4],[1,3]");
2123
assertEquals(1, solution1.eraseOverlapIntervals(intervals));
24+
assertEquals(1, solution2.eraseOverlapIntervals(intervals));
25+
}
26+
27+
@Test
28+
public void test2() {
29+
int[][] intervals = CommonUtils.convertLeetCodeIrregularLengths2DArrayInputIntoJavaArray("[-52,31],[-73,-26],[82,97],[-65,-11],[-62,-49],[95,99],[58,95],[-31,49],[66,98],[-63,2],[30,47],[-40,-26]");
30+
assertEquals(7, solution1.eraseOverlapIntervals(intervals));
31+
assertEquals(7, solution2.eraseOverlapIntervals(intervals));
2232
}
2333

2434
}

0 commit comments

Comments
 (0)