Skip to content

Instantly share code, notes, and snippets.

@zsh-89
Created October 29, 2013 15:09
Show Gist options
  • Save zsh-89/7216466 to your computer and use it in GitHub Desktop.
Save zsh-89/7216466 to your computer and use it in GitHub Desktop.
Leetcode: Merge Intervals
class Solution {
public:
struct InCmp {
bool operator()(const Interval & x, const Interval & y) const {
return x.start < y.start;
}
};
vector<Interval> merge(vector<Interval> &v) {
if (v.size() == 0) return v;
InCmp cmp;
sort(v.begin(), v.end(), cmp);
int emax = v[0].end; Interval intv = v[0];
vector<Interval> ans;
for (int i = 1; i < v.size(); ++i) {
if (v[i].start > emax) {
ans.push_back(intv);
intv = v[i];
emax = v[i].end;
}
else {
emax = max(emax, v[i].end);
intv.end = emax;
}
}
ans.push_back(intv);
return ans;
}
};
@eclipselu
Copy link

sort一遍维护rightmax(区间右值)是核心.

不错的做法,我的方法是比较Naive的方法,看起来没那么美观

@zsh-89
Copy link
Author

zsh-89 commented Oct 30, 2013

sort一遍维护rightmax(区间右值)是核心.

不错的做法,我的方法是比较Naive的方法,看起来没那么美观

其实思路是一样的, 就是你的循环不需要两层, 而我不需要endmax变量, 它已经隐含在{当前区间}中了.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment