Python解法:
def merge(intervals): intervals = sorted(intervals) res = [] n = len(intervals) i = 0 while i < n: left = intervals[i][0] right = intervals[i][1] while i < n-1 and intervals[i+1][0] <= right: i += 1 right = max(intervals[i][1], right) res.append([left, right]) i += 1 return res print(merge([[1,2],[3,8],[6,4],[15,18]]))
C++解法:
class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { vector<vector<int>> res; if(intervals.size() == 0) return res; sort(intervals.begin(), intervals.end()); int i = 0; vector<int> temp {0, 0}; while(i < intervals.size()){ int left = intervals[i][0]; int right = intervals[i][1]; while(i < intervals.size() - 1 && right >= intervals[i+1][0]){ ++i; right = max(right, intervals[i][1]); } ++i; temp[0] = left; temp[1] = right; res.push_back(temp); } return res; } bool compare(vector<int>& a, vector<int>&b){ return a[0] < b[0]; } };