Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sort(intervals.begin(), intervals.end()); //need to sort it first
- //l and r stores our current interval, starting with the first in the array
- int l = intervals[0].first, r = intervals[0].second;
- for (int i=1; i<intervals.size(); i++) {
- if (intervals[i].first > r) {
- //this condition means interval 'i' is out of our current (l, r) interval, so our old (l,r) is done
- merged.push_back(make_pair(l, r));
- // We start a new interval with information from intervals[i]:
- l = intervals[i].first; r = intervals[i].second;
- } else {
- //else, it means that the interval intersects (because it's sorted), so we just update the 'r' value with the maximum, merging the interval (l,r) with intervals[i]
- r = max(r, intervals[i].second);
- }
- merged.push_back(make_pair(l,r)); //push the last ones we were checking
- }
Advertisement
Add Comment
Please, Sign In to add comment