欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode] Insert Interval

程序员文章站 2024-03-01 09:01:40
...

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]

Solution

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
 public:
  vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
    vector<Interval> v;
    int i = 0, s, e;
    if (intervals.size() == 0 || newInterval.end < intervals[0].start) {
      //需要插入的区间结束比第一个区间开始要小,直接插入第一个区间
      v.push_back(newInterval);
    } else if (newInterval.start > intervals[intervals.size() - 1].end) {
      //需要插入的区间开始比最后一个区间的结束要大,直接插入最后一个区间
      intervals.push_back(newInterval);
      return intervals;
    } else {
      //需要插入的区间在中间时的情况
      for (; i < intervals.size() && intervals[i].end < newInterval.start;
           ++i) {
        v.push_back(intervals[i]);
      }
      //运行到这里 intervals[i - 1].end < newInterval.start <= intervals[i].end
      //取newInterval.start 和intervals[i].start中最小的。
      s = intervals[i].start < newInterval.start ? intervals[i].start
                                                 : newInterval.start;
      for (; i < intervals.size() && intervals[i].start <= newInterval.end; ++i)
        ;
      //运行到这里 intervals[i - 1].start <= newInterval.end < intervals[i].start
      //取newInterval.end和intervals[i-1].end中最大的。
      e = intervals[i - 1].end < newInterval.end ? newInterval.end
                                                 : intervals[i - 1].end;
      if (s <= e) {
        v.push_back(Interval(s, e));
      }
    }
    //剩余的全部放到最后。
    for (; i < intervals.size(); ++i) {
      v.push_back(intervals[i]);
    }

    return v;
  }
};
相关标签: cpp