Leetcode: Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

比较简单,排序之后遍历即可。注意比较函数需要是global或者static的,cplusplus上说的不清楚。

/**
 * 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 interval_less(Interval i1, Interval i2) {
        return i1.start < i2.start;
    }
    
    vector<Interval> merge(vector<Interval> &intervals) {
        sort(intervals.begin(), intervals.end(), interval_less);
        
        vector<Interval> result;
        if (intervals.empty()) {
            return result;
        }
        
        int start = intervals[0].start;
        int end = intervals[0].end;
        for (int i = 1; i < intervals.size(); ++i) {
            if (end >= intervals[i].start) {
                end = max(intervals[i].end, end);
            }
            else {
                result.push_back(Interval(start, end));
                start = intervals[i].start;
                end = intervals[i].end;
            }
        }
        result.push_back(Interval(start, end));
        
        return result;
    }
};

你可能感兴趣的:(LeetCode)