General • Asked over 4 years ago by Anonymous
This is the main discussion thread generated for A Close Look At Merging Intervals.
If no periods can be merged, doesn't this algo drop all but the last one? I think you are missing a second append...
> This part is a little hacky. Now the top of the stack can again be overlapping with new_item.
As we are are sorting the intervals before merging, how is it possible that the top of the stack will again be overlapping with the new_item(newly merged item)?
vector> merge(vector>& intervals) {
sort(intervals.begin(), end(intervals));
vector> ret = {intervals[0]};
for (int i = 1; i < intervals.size(); i++) {
vector &last = ret[ret.size() - 1];
const vector &next = intervals[i];
if (next[0] > last[1]) {
ret.push_back(next);
continue;
}
last[1] = max(last[1], next[1]);
}
return ret;
}
Something like this seems sufficient with out needing to iterate over a while loop to nestedly compare against the top of the stack.
Please let me know if i am missing something here.