Insert Intervals

LeetCode #57


Description:

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:

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */

Idea:

compare newInterval和vector里的elements,如果没有overlap,就要么insert,返回,要么往后看。如果有overlap,就更新newInterval,然后删除element。然后再看怎么insert newInterval。

std::vector::insert
Return value:
An iterator that points to the first of the newly inserted elements.

std::vector::erase
Return value:
An iterator pointing to the new location of the element that followed the last element erased by the function call.

Code:

class Solution {
public:
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        auto it=intervals.begin();

        while(it != intervals.end()){
            if(newInterval.end < it->start){
                intervals.insert(it, newInterval);
                return intervals;
            }
            else if(newInterval.start > it->end){
                it++;
            }
            else{
                // adjust newInterval, and remove element in intervals
                newInterval.start = min(it->start, newInterval.start);
                newInterval.end = max(it->end, newInterval.end);
                it = intervals.erase(it);
            }
        }

        intervals.insert(intervals.end(), newInterval);
        return intervals;
    }
};

results matching ""

    No results matching ""