您的位置:首页 > 其它

leetcode Merge Intervals

2013-10-26 15:52 387 查看
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]
.

First, this is not a problem about segment tree. Don't be hasty before you make decisions.

Second, the problem is how to sort. Give two ways in the following passage:

/**
 * 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 cmp {
 public:
  bool operator()(Interval a, Interval b) {
    return a.start == b.start?(a.end < b.end):(a.start < b.start);
  }
};
class Solution {
 public:
  vector<Interval> merge(vector<Interval> &intervals) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    if (intervals.size() < 1)
      return intervals;
      
    vector<Interval> res;
    sort(intervals.begin(), intervals.end(), cmp());
    int i, j;
    Interval cur(intervals[0].start, intervals[0].end);
    for (i = 1; i < intervals.size(); ++i) {
      if (intervals[i].start > cur.end) {
        res.push_back(cur);
        cur.start = intervals[i].start;
        cur.end = intervals[i].end;
      }
      else
        cur.end = max(intervals[i].end, cur.end);
    }
    res.push_back(cur);
    return res;
  }
};


/**
 * 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 cmp {
 public:
  bool operator()(Interval a, Interval b) {
    return a.start == b.start?(a.end < b.end):(a.start < b.start);
  }
};
*/
bool operator<(Interval a, Interval b) {
  return a.start == b.start?(a.end < b.end):(a.start < b.start);
}
class Solution {
 public:

  vector<Interval> merge(vector<Interval> &intervals) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    if (intervals.size() < 1)
      return intervals;
      
    vector<Interval> res;
    sort(intervals.begin(), intervals.end());
    int i, j;
    Interval cur(intervals[0].start, intervals[0].end);
    for (i = 1; i < intervals.size(); ++i) {
      if (intervals[i].start > cur.end) {
        res.push_back(cur);
        cur.start = intervals[i].start;
        cur.end = intervals[i].end;
      }
      else
        cur.end = max(intervals[i].end, cur.end);
    }
    res.push_back(cur);
    return res;
  }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: