Leetcode[56] Merge Intervals

Submission
/**
 * 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:
    static bool comp(Interval& a, Interval& b) {return a.start < b.start;}

    vector merge(vector& intervals) {
        if(intervals.empty()) return vector();
        vector result;
        sort(intervals.begin(), intervals.end(), comp);
        Interval last = Interval(intervals[0].start, intervals[0].end);
        for(int i = 1; i < intervals.size(); i++) {
            if(intervals[i].start <= last.end) {
                if(intervals[i].end > last.end) {
                    last.end = intervals[i].end;
                }
            } else {
                result.push_back(last);
                last.start = intervals[i].start;
                last.end = intervals[i].end;
            }
        }
        result.push_back(last);
        return result;
    }
};
Time

13ms

Explanation

First sort the array according to interval's start value in ascending order. Iterate starts at the first interval, and keep a reference of the last checked/merged interval. For each new interval, check if it should be merged; if not, add the current last interval to result.

Notes
  • c++ vector's push_back function makes a copy of the argument.
  • left reference & cannot be reassigned.

你可能感兴趣的:(Leetcode[56] Merge Intervals)