LeetCode 56. Merge Intervalse
阿新 • • 發佈:2018-12-12
題解
檢驗區間交疊,思路比較直觀,先排序再比較,看程式碼。 前面我的,後面的最精煉。
O(n^2)
class Solution {
public:
static bool cmp(Interval &a,Interval &b){
return a.start < b.start;
}
bool used[50000];
vector<Interval> res;
vector<Interval> merge(vector<Interval>& intervals) {
sort (intervals.begin(),intervals.end(),cmp);
memset(used,false,sizeof(used));
int st,ed;
for(int i=0;i<intervals.size();i++){
if( !used[i] ){
st = intervals[i].start;
ed = intervals[i].end;
for (int j=i+1;j<intervals.size();j++){
if( used[j] ) continue;
if(intervals[j].start <= ed && intervals[j].end >ed){
used[j]= true;
ed = intervals[j].end;
} else if(intervals[j].start >= st && intervals[j].end <=ed){
used[j]= true;
}
}
used[i]= true;
res.push_back(Interval(st,ed) );
}
}
return res;
}
};
O(nlogn)
vector<Interval> merge(vector<Interval>& ins) {
if (ins.empty()) return vector<Interval>{};
vector<Interval> res;
sort(ins.begin(), ins.end(), [](Interval a, Interval b){return a.start < b.start;});
res.push_back(ins[0]);
for (int i = 1; i < ins.size(); i++) {
if (res.back().end < ins[i].start) res.push_back(ins[i]);
else
res.back().end = max(res.back().end, ins[i].end);
}
return res;
}