Easy C++ Solution (Useful but nothing new)


  • 0
    G
        vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
            struct cmp {
                bool operator () (Interval i1, Interval i2) {
                    return i1.end < i2.start;
                }
            };
            auto ranges = equal_range(intervals.begin(), intervals.end(), newInterval, cmp());  // find all overlapping ranges
            if (ranges.first == ranges.second) {                // no overlapping ranges
                intervals.insert(ranges.first, newInterval);
            } else {                                            // at least one overlapping range
                ranges.first->start = min(newInterval.start, ranges.first->start);      // extend the first overlapping range
                ranges.first->end = max(newInterval.end, (ranges.second - 1)->end);
                intervals.erase(++(ranges.first), ranges.second);                       // remove the remaining ranges
            }
            return intervals;
        }
    

Log in to reply
 

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