Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public int[][] merge(int[][] intervals) {
        if (intervals == null || intervals.length == 0) {
            return new int[][]{};
        }
        // Sorting `intervals` based on 1st element of each interval makes the solution easier.
        Arrays.sort(intervals, Comparator.comparingInt(item -> item[0]));
        List<int[]> tmpRet = new ArrayList<>();
        tmpRet.add(intervals[0]);
        
        for (int i = 0; i < intervals.length; i++) {
            int[] last = tmpRet.get(tmpRet.size() - 1);
            if (intervals[i][0] <= last[1]) {
                last[1] = Math.max(last[1], intervals[i][1]);
            } else {
                tmpRet.add(intervals[i]);
            }
        }
        return tmpRet.toArray(new int[tmpRet.size()][2]);
    }
}