|
1 | 1 | class Solution {
|
2 | 2 | public int[][] merge(int[][] intervals) {
|
3 |
| - Arrays.sort(intervals, new Comparator<int[]>(){ |
4 |
| - public int compare(int[] o1, int[] o2) { |
5 |
| - int c = o1[0] - o2[0]; |
6 |
| - if (c != 0) { |
7 |
| - return c; |
8 |
| - } |
9 |
| - return o1[1] - o2[1]; |
10 |
| - } |
11 |
| - }); |
12 |
| - List<int[]> intervalList = new ArrayList<>(); |
13 |
| - int end = 0; |
14 |
| - int n = intervals.length; |
15 |
| - int currStart = -1; |
16 |
| - int currEnd = -1; |
17 |
| - while (end < n) { |
18 |
| - if (currStart == -1 && currEnd == -1) { |
19 |
| - currStart = intervals[end][0]; |
20 |
| - currEnd = intervals[end][1]; |
21 |
| - end++; |
22 |
| - } |
23 |
| - if (end < n) { |
24 |
| - if (currEnd >= intervals[end][0]) { |
25 |
| - currEnd = Math.max(intervals[end][1], currEnd); |
26 |
| - end++; |
27 |
| - } |
28 |
| - else { |
29 |
| - intervalList.add(new int[]{currStart, currEnd}); |
30 |
| - currStart = -1; |
31 |
| - currEnd = -1; |
32 |
| - } |
33 |
| - } |
34 |
| - if (end == n && currStart != -1 && currEnd != -1) { |
35 |
| - intervalList.add(new int[]{currStart, currEnd}); |
| 3 | + Arrays.sort(intervals, Comparator.comparingInt((int[] o) -> o[0]).thenComparingInt(o -> o[1])); |
| 4 | + List<int[]> mergedIntervals = new ArrayList<>(); |
| 5 | + int idx = 0; |
| 6 | + while (idx < intervals.length) { |
| 7 | + int currentStart = intervals[idx][0]; |
| 8 | + int currentEnd = intervals[idx][1]; |
| 9 | + idx++; |
| 10 | + while (idx < intervals.length && intervals[idx][0] <= currentEnd) { |
| 11 | + currentEnd = Math.max(intervals[idx][1], currentEnd); |
| 12 | + idx++; |
36 | 13 | }
|
| 14 | + mergedIntervals.add(new int[]{currentStart, currentEnd}); |
37 | 15 | }
|
38 |
| - int[][] ans = new int[intervalList.size()][2]; |
39 |
| - for (int i = 0; i < intervalList.size(); i++) { |
40 |
| - ans[i] = intervalList.get(i); |
| 16 | + int[][] result = new int[mergedIntervals.size()][2]; |
| 17 | + for (int i = 0; i < mergedIntervals.size(); i++) { |
| 18 | + result[i] = mergedIntervals.get(i); |
41 | 19 | }
|
42 |
| - return ans; |
| 20 | + return result; |
43 | 21 | }
|
44 | 22 | }
|
0 commit comments