My C++ Solution ;)


  • 0
    V
    /**
     * Definition for an interval.
     * struct Interval {
     *     int start;
     *     int end;
     *     Interval() : start(0), end(0) {}
     *     Interval(int s, int e) : start(s), end(e) {}
     * };
     */
     
     bool compareInterval(Interval interval1,Interval interval2) {
         return interval1.start < interval2.start;
     }
    class Solution {
    public:
       vector<Interval> insert(vector<Interval>& intervals, Interval newI) {
            int intervalSize = intervals.size();
            vector<Interval> resultInterval;
            if(intervalSize == 0) {
                resultInterval.push_back(newI);
                return resultInterval;   
            }
            for(int i=0;i<intervalSize;i++) {
                if(compareInterval(intervals[i],newI)) {
                    swap(intervals[i],newI);
                }
                // Overlapping Interval
                if(newI.end >= intervals[i].start) {
                    newI.start = min(newI.start, intervals[i].start);
                    newI.end = max(newI.end, intervals[i].end);
                }
                // newI < interval element
                else if(newI.end < intervals[i].start) {
                    resultInterval.push_back(newI);
                    newI = intervals[i];
                }
                // Interval element < newI
                else {
                    resultInterval.push_back(intervals[i]);
                }
            }
            resultInterval.push_back(newI);
            return resultInterval;
        }
    };

Log in to reply
 

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