Guest User

Untitled

a guest
Aug 31st, 2014
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. sort(intervals.begin(), intervals.end()); //need to sort it first
  2. //l and r stores our current interval, starting with the first in the array
  3. int l = intervals[0].first, r = intervals[0].second;
  4. for (int i=1; i<intervals.size();  i++) {
  5.     if (intervals[i].first > r) {
  6.        //this condition means interval 'i' is out of our current (l, r) interval, so our old (l,r) is done
  7.        merged.push_back(make_pair(l, r));
  8.        // We start a new interval with information from intervals[i]:
  9.        l = intervals[i].first; r = intervals[i].second;
  10.     } else {
  11.         //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]
  12.        r = max(r, intervals[i].second);
  13.     }
  14.     merged.push_back(make_pair(l,r)); //push the last ones we were checking
  15. }
Advertisement
Add Comment
Please, Sign In to add comment