【LeetCode】#56合并区间(Merge Intervals)
题目描述
给出一个区间的集合,请合并所有重叠的区间。
示例
示例 1:
输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
Description
Given a collection of intervals, merge all overlapping intervals.
Example
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
解法
class Solution {
public List<Interval> merge(List<Interval> intervals) {
int n = intervals.size();
int[] starts = new int[n];
int[] ends = new int[n];
for(int i=0; i<n; i++){
starts[i] = intervals.get(i).start;
ends[i] = intervals.get(i).end;
}
Arrays.sort(starts);
Arrays.sort(ends);
List<Interval> res = new ArrayList<>();
for(int i=0,j=0; i<n; i++){
if(i==n-1 || starts[i+1]>ends[i]){
res.add(new Interval(starts[j], ends[i]));
j = i+1;
}
}
return res;
}
}