Share my Solution : 16 ms beats 100 % CPP submissions


  • 0
    A

    class Solution {
    public:
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {

        vector<Interval> ret;
        bool isInserted=false;  // merged interval/ new interval
        
        for(int i=0;i<intervals.size();i++)
        {
           // before   
           if(intervals[i].start <= newInterval.start)
           {
                if(newInterval.start <= intervals[i].end)
                {
                    newInterval.start=min(newInterval.start,intervals[i].start);
                    newInterval.end=max(newInterval.end,intervals[i].end);
                }
                else // dont merge
                {
                    ret.push_back(intervals[i]);
                }
           }
           else // after
           {
               if(intervals[i].start <= newInterval.end)
               {
                    newInterval.start=min(newInterval.start,intervals[i].start);
                    newInterval.end=max(newInterval.end,intervals[i].end);   
               }
               else
               {
                   if(!isInserted)
                   {
                        ret.push_back(newInterval);
                        isInserted=true;
                   }
                   ret.push_back(intervals[i]); 
               }
           }
        }
        if(!isInserted)
           ret.push_back(newInterval); 
        
        return ret;
    }
    

    };


Log in to reply
 

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