4/15/2014

Leetcode -- Insert Interval

We can just copy the code from merge interval, only need to insert the new interval and then merge
/**
 * 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 insert(vector &intervals, Interval newInterval) {
        vector result;
        intervals.emplace_back(newInterval);
        sort(intervals.begin(), intervals.end(), [](Interval i1, Interval i2) {
            return i1.start < i2.start;
        });

        Interval interval(intervals[0]);
        for(int i = 1; i < intervals.size(); ++i) {
            if(intervals[i].start <= interval.end) {
                interval.end = max(intervals[i].end, interval.end);
            } else {
                result.emplace_back(interval);                
                interval = intervals[i];
            }
        }
        result.emplace_back(interval);
        
        return result;
    }
};

No comments: