C++ ,12ms, O(logn)/O(1),beats 85%


  • 0
    S
    /**
     * Definition for an interval.
     * struct Interval {
     *     int start;
     *     int end;
     *     Interval() : start(0), end(0) {}
     *     Interval(int s, int e) : start(s), end(e) {}
     * };
     */
    class Solution {
    public:
        vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
            auto begin = lower_bound(intervals.begin(), intervals.end(), newInterval, [](const Interval& a, const Interval& b)->bool{
                return a.end < b.start;
            });
            if (begin == intervals.end()) {
                intervals.push_back(newInterval);
                return intervals;
            }
            
            auto end = upper_bound(begin, intervals.end(), newInterval, [](const Interval& a, const Interval& b)->bool{
                return b.start > a.end;
            });
            if (end == intervals.begin()) {
                intervals.insert(end, newInterval);
                return intervals;
            }
            --end;
            if (newInterval.end < begin->start) {
                intervals.insert(begin, newInterval);
                return intervals;
            }
    
            begin->start = min(begin->start, newInterval.start);
            begin->end = max(end->end, newInterval.end);
            intervals.erase(begin + 1, end + 1);
            return intervals;
        }
    };
    

Log in to reply
 

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