56 - Merge Intervals

#medium

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1:
Input: intervals = [ [1,3],[2,6],[8,10],[15,18] ]
Output: [ [1,6],[8,10],[15,18] ]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

Example 2:
Input: intervals = [ [1,4],[4,5] ]
Output: [ [1,5] ]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

class Solution {
public:

    static bool cmp( vector<int> & a, vector<int> & b ) {
        if ( a[0] == b[0] ) return a[1] < b[1];
        return a[0] < b[0];
    }

    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>> result;
        sort( intervals.begin(), intervals.end(), cmp );
        result.push_back( intervals[0] );
        int max_value = intervals[0][1];
        int min_value;
        for ( int i = 1; i < intervals.size(); i++ ) {
            if ( intervals[i][0] <= max_value ) {
                vector<int> temp = result[result.size()-1];
                temp[1] = max( intervals[i][1], max_value ); // 需考慮 [[1,4],[2,3]] = [[1,4]]
                result[result.size()-1] = temp;
                max_value =  temp[1];
            }            
            else {
                result.push_back( intervals[i] );
                max_value =  intervals[i][1];
            }

        }

        return result;
    }