思路
首先要注意的是,所給的 interval 陣列是無序的。解法一要先將陣列按左邊界大小排序。新建一個空 List 儲存所有 merge 後的 intervals。然後遍歷排序好的陣列,如果其中的 interval 和 list 中最後一個 interval 有重合區域,將 list 中的這個 interval 擴充套件。如果包含在內,則不發生變化。 如果沒有重合區域,就將這個新的 interval 新增進 list 中。
解法一
/*
Sort the intervals according to their start value;
Initialize a list newInterval to store result intervals;
Set the first value of the list to be the first element newInterval in the sorted interval array.
for (intervals[0], intervals[1], ... ,intervals[n - 1])
// If overlap, set the larger end to be the end for newInterval;
if (intervals[i][0] >= newInterval[0])
end of last result interval = max(intervals[i][1], newInterval[1]);
else
newInterval = intervals[i];
add(newInterval);
endif
return the result interval;
*/
class Solution {
public int[][] merge(int[][] intervals) {
// return the original array if its length <= 1
if (intervals.length <= 1) {
return intervals;
}
Arrays.sort(intervals,(i1, i2)->Integer.compare(i1[0], i2[0])); // O(nlogn)
List<int[]> result = new ArrayList<>();
int[] newInterval = intervals[0];
result.add(newInterval);
for (int[] interval : intervals) {
// Overlap
if (interval[0] <= newInterval[1]) {
// Update the end of the last interval in the result
result.get(result.size() - 1)[1] = Math.max(interval[1], newInterval[1]);
}
// Not overlap, just add the interval to the result.
else {
newInterval = interval;
result.add(newInterval);
}
}
return result.toArray(new int[result.size()][2]);
}
}