给定一个数组的容器,将容器中的数组代表一个区间,如果有区间重叠的,将他们融合为一个大的区间,输出最终的区间。
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].
思路:
先将容器排序,按照数组区间的起点排序,则处理起来就方便了。设区间的起点为start,区间终点为end,如果下一个区间的起点 next-start比当前区间的 end 小,且 next-end > end,则更新区间为:[ start , next-end ],反之:如果下一个区间的 next-start > end,则说明不能融合,将当前区间[start, end] 加入到结果容器中。
class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { if (intervals.empty() || intervals[0].size() == 0) return {}; vector<vector<int>> res; sort(intervals.begin(), intervals.end()); int n = intervals.size(), start = intervals[0][0], end = intervals[0][1]; for (int i = 0; i < n; i++) { if (intervals[i][0] <= end) { if(intervals[i][1] > end) end = intervals[i][1]; } else { res.push_back({ start,end }); start = intervals[i][0]; end = intervals[i][1]; } } res.push_back({ start,end }); return res; } };
Java 版:
class Solution { public int[][] merge(int[][] intervals) { if(intervals.length == 0 || intervals[0].length == 0) return new int[][]{}; Arrays.sort(intervals, (v1,v2)-> v1[0] - v2[0]); // 排序 List<int[]> res = new ArrayList<>(); int n = intervals.length, start = intervals[0][0], end = intervals[0][1]; for(int i = 0; i < n; i++){ if(intervals[i][0] <= end) end = Math.max(end, intervals[i][1]); else{ res.add(new int[]{start, end}); start = intervals[i][0]; end = intervals[i][1]; } } res.add(new int[]{start, end}); return res.toArray(new int[0][]); } }