题目:
给出若干闭合区间,合并所有重叠的部分。
样例:
给出的区间列表 => 合并后的区间列表:
[ [
[1, 3], [1, 6],
[2, 6], => [8, 10],
[8, 10], [15, 18]
[15, 18] ]
]
答案:
考虑输入可能为空的情况;先排序再遍历即可。
代码:
1 /** 2 * Definition of Interval: 3 * classs Interval { 4 * int start, end; 5 * Interval(int start, int end) { 6 * this->start = start; 7 * this->end = end; 8 * } 9 */ 10 11 #include <algorithm> 12 13 using std::sort; 14 15 bool cmp(const Interval &a, const Interval &b) 16 { 17 return a.start < b.start; 18 } 19 20 class Solution { 21 public: 22 /** 23 * @param intervals: interval list. 24 * @return: A new interval list. 25 */ 26 vector<Interval> merge(vector<Interval> &intervals) { 27 int i,j; 28 vector<Interval> ans; 29 if(intervals.empty()) 30 { 31 return ans; 32 } 33 sort(intervals.begin(),intervals.end(),cmp); 34 35 ans.push_back(intervals[0]); 36 37 bool join; 38 for(i = 1; i < intervals.size(); ++ i) 39 { 40 join = false; 41 for(j = 0; j < ans.size(); ++ j) 42 { 43 if(intervals[i].start <= ans[j].end && intervals[i].end >= ans[j].end) 44 { 45 ans[j].end = intervals[i].end; 46 join = true; 47 break; 48 } 49 50 if(intervals[i].end <= ans[j].end) 51 { 52 join = true; 53 break; 54 } 55 } 56 57 if(!join) 58 { 59 ans.push_back(intervals[i]); 60 } 61 } 62 63 return ans; 64 } 65 };