Easy C++ Solution


  • 0
    Y

    This solution merge the overlapping intervals to this newInterval to make it a non-overlapping interval and insert to the vactor.

    class Solution {
    public:
        vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
            vector<Interval> ans;
            bool if_insert = false;
            for (auto interval : intervals) {
                if (interval.end < newInterval.start)
                    ans.push_back(interval);
                else if (interval.start > newInterval.end) {
                    if (!if_insert) {
                        ans.push_back(newInterval);
                        if_insert = true;
                    }
                    ans.push_back(interval);
                }
                else {
                    newInterval.start = min(newInterval.start, interval.start);
                    newInterval.end = max(newInterval.end, interval.end);
                }
                
            }
            if (!if_insert) ans.push_back(newInterval);
            
            return ans;
        }
    };
    
    

Log in to reply
 

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