C++ 16ms solution


  • 0
    X
    class Solution {
    public:
        vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
            int i = 0;
            while (i < intervals.size() && intervals[i].start <= newInterval.start) i++;
            intervals.insert(intervals.begin() + i, newInterval);
            
            for (int k = max(i - 1, 0); k + 1 < intervals.size(); k++) {
                if (intervals[k].end >= intervals[k+1].start) {
                    intervals[k+1].start = intervals[k].start;
                    intervals[k+1].end = max(intervals[k].end, intervals[k+1].end);
                    intervals[k].start = intervals[k].end = -1;
                }
            }
    
            vector<Interval> res;
            for (int k = 0; k < intervals.size(); k++) {
                if (intervals[k].start != -1) res.push_back(intervals[k]);
            }
            return res;
        }
    };

Log in to reply
 

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