Clean and Fast C++ Code

  • 1
    class Solution {
        vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
            vector<Interval> res;
            int n = intervals.size();
            int i = 0;
            while (i < n) {
                if (intervals[i].end < newInterval.start) // push those who go front of newInterval
                else if (intervals[i].start > newInterval.end) // break to push newInterval and the rest
                else { // merge newInterval and those overlapping with it
                    newInterval.start = min(newInterval.start, intervals[i].start);
                    newInterval.end = max(newInterval.end, intervals[i].end);
            while (i < n) res.push_back(intervals[i++]);
            return res;

Log in to reply

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