Skip to content

Commit 9ca9c85

Browse files
refactor 435
1 parent 38589ac commit 9ca9c85

File tree

2 files changed

+12
-16
lines changed

2 files changed

+12
-16
lines changed

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

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,25 +10,20 @@ public static class Solution1 {
1010
* credit:: https://discuss.leetcode.com/topic/65828/java-solution-with-clear-explain
1111
* and https://discuss.leetcode.com/topic/65594/java-least-is-most
1212
* Sort the intervals by their end time, if equal, then sort by their start time.
13+
* Then merge based on ending time.
1314
*/
1415
public int eraseOverlapIntervals(int[][] intervals) {
15-
Collections.sort(Arrays.asList(intervals), (o1, o2) -> {
16-
if (o1[1] != o2[1]) {
17-
return o1[1] - o2[1];
16+
Arrays.sort(intervals, (a, b) -> a[1] != b[1] ? a[1] - b[1] : a[0] - b[0]);
17+
int erasures = 0;
18+
int end = intervals[0][1];
19+
for (int i = 1; i < intervals.length; i++) {
20+
if (intervals[i][0] < end) {
21+
erasures++;
1822
} else {
19-
return o2[0] - o1[0];
20-
}
21-
});
22-
int end = Integer.MIN_VALUE;
23-
int count = 0;
24-
for (int[] interval : intervals) {
25-
if (interval[0] >= end) {
26-
end = interval[1];
27-
} else {
28-
count++;
23+
end = intervals[i][1];
2924
}
3025
}
31-
return count;
26+
return erasures;
3227
}
3328
}
3429

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.fishercoder;
22

3+
import com.fishercoder.common.utils.CommonUtils;
34
import com.fishercoder.solutions._435;
45
import org.junit.BeforeClass;
56
import org.junit.Test;
@@ -16,8 +17,8 @@ public static void setup() {
1617

1718
@Test
1819
public void test1() {
19-
int[][] intervals = new int[][]{new int[]{1, 100}, new int[]{11, 22}, new int[]{1, 11}, new int[]{2, 12}};
20-
assertEquals(2, solution1.eraseOverlapIntervals(intervals));
20+
int[][] intervals = CommonUtils.convertLeetCodeIrregularLengths2DArrayInputIntoJavaArray("[1,2],[2,3],[3,4],[1,3]");
21+
assertEquals(1, solution1.eraseOverlapIntervals(intervals));
2122
}
2223

2324
}

0 commit comments

Comments
 (0)