Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Created June 14, 2019 15:15
Show Gist options
  • Save yangpeng-chn/1a5c7d830474068f066beaae91c7c53b to your computer and use it in GitHub Desktop.
Save yangpeng-chn/1a5c7d830474068f066beaae91c7c53b to your computer and use it in GitHub Desktop.
Merge Intervals
vector<vector<int>> mergeIntervals(vector<vector<int>>& intervals) {
if (intervals.empty()) return {};
sort(intervals.begin(), intervals.end());
vector<vector<int>> res{intervals[0]};
for (int i = 1; i < intervals.size(); ++i) {
if (res.back()[1] < intervals[i][0]) { //doesn't overlap, push current interval
res.push_back(intervals[i]);
} else {
res.back()[1] = max(res.back()[1], intervals[i][1]); //overlap, update end
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment