Crystal clear c++ solution


  • 2
    L
    class Solution {
     public:
      vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        int i = 0, n = intervals.size();
        int start = newInterval.start;
        int end = newInterval.end;
        vector<Interval> res;
    
        // add all the intervals ends before newInterval.start to result
        while (i < n && intervals[i].end < start) {
          res.push_back(intervals[i]);
          ++i;
        }
    
        // expand newInterval maybe
        if (i < n) start = min(start, intervals[i].start);
        while (i < n && intervals[i].start <= end) ++i;
        
        if (i - 1 >= 0) end = max(intervals[i-1].end, end);
        res.push_back(Interval(start, end));
    
        // add all the intervals starts after newInterval.end to result
        while (i < n) {
          res.push_back(intervals[i]);
          ++i;
        }
    
        return res;
      }
    };

  • -2
    P

    so great and easy to understand!


Log in to reply
 

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