56. Merge Intervals

qqiangwu
qqiangwu
Feb 23, 2017 · 1 min read

Using induction. If range [0, k) is merged, how to cope with element A[k]. It’s trivial. The whole process cost O(n).

Wait… Is the input sorted? No. So we need sort it first. Then we have O(nlogn + n)

Can we not sort the input? Then in the induction step, finding the proper position for A[k] needs O(logn). If a shift is involved, O(n) is required.

class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
std::vector<Interval> result;

std::sort(intervals.begin(), intervals.end(), [](const Interval a, const Interval b){
return a.start < b.start;
});

for (const auto interval: intervals) {
if (result.empty()) {
result.push_back(interval);
} else {
auto& prev = result.back();

if (isOverlapped(prev, interval)) {
prev.end = std::max(prev.end, interval.end);
} else {
result.push_back(interval);
}
}
}

return result;
}

bool isOverlapped(const Interval a, const Interval b) {
return a.start <= b.start && b.start <= a.end;
}
};

DS Adventure

I wrote both code and poetry

qqiangwu

Written by

https://github.com/qqiangwu

DS Adventure

I wrote both code and poetry

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade