Merge Intervals

描述

Given a collection of intervals, merge all overlapping intervals.

For example,Given [1,3],[2,6],[8,10],[15,18],return [1,6],[8,10],[15,18]

分析

复用一下Insert Intervals的解法即可,创建一个新的interval集合,然后每次从旧的里面取一个interval出来,然后插入到新的集合中。

代码

  1. // Merge Interval
  2. //复用一下Insert Intervals的解法即可
  3. // 时间复杂度O(n1+n2+...),空间复杂度O(1)
  4. class Solution {
  5. public:
  6. vector<Interval> merge(vector<Interval> &intervals) {
  7. vector<Interval> result;
  8. for (int i = 0; i < intervals.size(); i++) {
  9. insert(result, intervals[i]);
  10. }
  11. return result;
  12. }
  13. private:
  14. vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
  15. vector<Interval>::iterator it = intervals.begin();
  16. while (it != intervals.end()) {
  17. if (newInterval.end < it->start) {
  18. intervals.insert(it, newInterval);
  19. return intervals;
  20. } else if (newInterval.start > it->end) {
  21. it++;
  22. continue;
  23. } else {
  24. newInterval.start = min(newInterval.start, it->start);
  25. newInterval.end = max(newInterval.end, it->end);
  26. it = intervals.erase(it);
  27. }
  28. }
  29. intervals.insert(intervals.end(), newInterval);
  30. return intervals;
  31. }
  32. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/simulation/merge-intervals.html