Easily-understood one-pass C++ solution


  • 1
    M
    /**
     * 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> result;
            int n = intervals.size();
            result.push_back(newInterval);
            for (int i = 0; i < n; i++) {
                if (intervals[i].start > result.back().end) {
                    // back before interval[i]
                    result.push_back(intervals[i]);
                } else if (intervals[i].end < result.back().start) {
                    // interval[i] before back
                    Interval tmp = result.back();
                    result.pop_back();
                    result.push_back(intervals[i]);
                    result.push_back(tmp);
                } else {
                    // overlap
                    Interval tmp = result.back();
                    result.pop_back();
                    result.push_back(Interval(min(intervals[i].start, tmp.start), max(intervals[i].end, tmp.end)));
                }
            }
            return result;
           
        }
    };
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.