Monday, October 20, 2014

Insert Interval

idea: do it in a natural way.

vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
    vector<Interval> ret;
    int cur=0;
    int n= intervals.size();
    while(cur<n&&newInterval.start>intervals[cur].end)
        ret.push_back(intervals[cur++]);
    while(cur<n&&newInterval.end>=intervals[cur].start)
    {
        newInterval.start=min(newInterval.start,intervals[cur].start);
        newInterval.end=max(newInterval.end,intervals[cur].end);
        cur++;
    }
    ret.push_back(newInterval);
    while(cur<n)
        ret.push_back(intervals[cur++]);

    return ret;
}

No comments:

Post a Comment