1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Merge Intervals

Posted on 2013-12-30 18:22  1957  阅读(155)  评论(0编辑  收藏  举报
/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
     bool cmp1957(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(), cmp1957);
        vector<Interval> ans;
        if (intervals.size() < 1) return ans;
        int start = intervals[0].start;
        int end = intervals[0].end;
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals[i].start <= end) {
                end = max(end, intervals[i].end);
            } else {
                ans.push_back(Interval(start, end));
                start = intervals[i].start;
                end = intervals[i].end;
            }
        }
        ans.push_back(Interval(start, end));
        return ans;
    }
};

  

/**
 * 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:
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> ans;
        if (intervals.size() == 0) return ans;
        sort(intervals.begin(), intervals.end(), [&](const Interval& a, const Interval& b) {
            return a.start < b.start;
        });
        Interval tmp = *intervals.begin();
        for (int i = 1; i < intervals.size(); i++) {
           if (intervals[i].start <= tmp.end) {
               tmp.end = max(tmp.end, intervals[i].end);
           } else {
               ans.push_back(tmp);
               tmp = intervals[i];
           }
        }
        ans.push_back(tmp);
        return ans;
    }
};