Solution1
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if(intervals.size()==0) return {};
vector<vector<int>> res;
int len = intervals.size();
sort(intervals.begin(), intervals.end(), cmp);
res.push_back(intervals[0]);
for(int i=1; i<len; i++){
vector<int>& cur = intervals[i];
vector<int>& last = res.back();
if(cur[0]<=last[1]){
last[1] = max(last[1], cur[1]);
}else{
res.push_back(cur);
}
}
return res;
}
private:
static bool cmp( const vector<int>& v1, const vector<int>& v2){
return v1[0]<v2[0];
}
};
Solution 2
class Solution {
public:
typedef pair<int, int> PII;
vector<PII> segs;
vector<vector<int>> res;
vector<vector<int>> merge(vector<vector<int>>& intervals) {
for(auto&e : intervals)
segs.push_back({e[0], e[1]});
sort(segs.begin(), segs.end());
int l = -1, r = -1;
for(auto&e : segs){
if(e.first > r){
if(l != -1) res.push_back({l, r});
l = e.first;
r = e.second;
}else{
r = max(r, e.second);
}
}
if(l != -1) res.push_back({l, r});
return res;
}
};
py
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) == 0: return []
intervals = sorted(intervals, key = lambda x: x.start)
res = [intervals[0]]
for n in intervals[1:]:
if n.start <= res[-1].end: res[-1].end = max(n.end, res[-1].end)
else: res.append(n)
return res