LeetCode Merge Intervals

class Solution {
private:
    static int compare(const Interval& a, const Interval& b) {
        return a.start < b.start;
    }
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> res;
        int len = intervals.size();
        if (len < 1) return res;

        sort(intervals.begin(), intervals.end(), Solution::compare);
    
        Interval merged = intervals[0];
        for (int i=1; i<len; i++) {
            Interval& cur = intervals[i];
            if (merged.end >= cur.start) { // merge two intervals
                if (merged.end < cur.end) merged.end = cur.end;
            } else {
                res.push_back(merged);
                merged = cur;
            }
        }
        res.push_back(merged);

        return res;
    }
};

水一发

第二轮:

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].

 

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
// 22:56
 
class Comparator {
public:
    bool operator() (const Interval& a, const Interval& b) {
        return a.start < b.start;
    }    
};
 
class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        sort(intervals.begin(), intervals.end(), Comparator());
        vector<Interval> res;
        int len = intervals.size();
        if (len < 1) {
            return res;
        }
        Interval last = intervals[0];
        for (int i=1; i<len; i++) {
            Interval& cur = intervals[i];
            if (last.end >= cur.start) {
                last.start = min(last.start, cur.start);
                last.end = max(last.end, cur.end);
            } else {
                res.push_back(last);
                last = cur;
            }
        }
        res.push_back(last);
        return res;
    }
};

 在简化一些

class Comp {
public:
    bool operator()(const Interval& a, const Interval& b) {
        return a.start < b.start;
    }
};

class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> res;
        sort(intervals.begin(), intervals.end(), Comp());
        
        for (Interval& curr : intervals) {
            if (res.empty()) {
                res.push_back(curr);
                continue;
            }
            Interval& last = res.back();
            if (curr.start <= last.end) {
                last.end = max(last.end, curr.end);
            } else {
                res.push_back(curr);
            }
        }
        return res;
    }
};

 

posted @ 2014-05-29 19:21  卖程序的小歪  阅读(214)  评论(0编辑  收藏  举报