Simple C++ solution.


  • 0
    class Solution {
    public:
        vector<Interval> merge(vector<Interval>& intervals) {
            if (intervals.empty()) return intervals;
            vector<Interval> res;
    
            // Sort by start index.
            sort(intervals.begin(), intervals.end(), [](const Interval& a, const Interval& b) {
                return a.start < b.start;
            });
    
            res.push_back(intervals[0]);
            for (int i = 1; i < intervals.size(); ++i) {
                if (intervals[i].start <= res.back().end) {
                    // Update the last interval's end index if the intervals overlap.
                    res.back().end = max(res.back().end, intervals[i].end);
                } else {
                    // Just add a new interval.
                    res.push_back(intervals[i]);
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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