LeetCode56 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]
. (Hard)
分析:
前两天做google的笔试,中间有一道题用到关于区间merge的问题,就把leetcode上这两道区间合并题目先做一下。
思路就是先对每个区间的起始位置进行排序,然后维护一个left和right;
当intervals[i].start <= right时,说明依旧在当前维护的区间范围内,更新right;
当intervals[i].start > right时,说明维护的区间已经结束,把left,right生成Interval添加到result里,
并更新left,right为当前区间的start,end。
注意:cmp函数怎么写的问题,leetcode里有个solution类,写成static函数。
代码:
1 /** 2 * Definition for an interval. 3 * struct Interval { 4 * int start; 5 * int end; 6 * Interval() : start(0), end(0) {} 7 * Interval(int s, int e) : start(s), end(e) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 static bool cmp (const Interval& I1, const Interval& I2) { 13 return I1.start < I2.start; 14 } 15 public: 16 vector<Interval> merge(vector<Interval>& intervals) { 17 vector<Interval> result; 18 if (intervals.size() == 0) { 19 return result; 20 } 21 sort(intervals.begin(), intervals.end(), cmp); 22 int left = intervals[0].start, right = intervals[0].end; 23 for (int i = 1; i < intervals.size(); ++i) { 24 if (intervals[i].start <= right) { 25 right = max(right,intervals[i].end); 26 } 27 else { 28 result.push_back(Interval(left,right)); 29 left = intervals[i].start; 30 right = intervals[i].end; 31 } 32 } 33 result.push_back(Interval(left,right)); 34 return result; 35 } 36 };
最近学习C++11/14新标准,把做过这些题里的传递函数的用lambda表达式重新写一下
代码2:
1 /** 2 * Definition for an interval. 3 * struct Interval { 4 * int start; 5 * int end; 6 * Interval() : start(0), end(0) {} 7 * Interval(int s, int e) : start(s), end(e) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<Interval> merge(vector<Interval>& intervals) { 13 vector<Interval> result; 14 if (intervals.size() == 0) { 15 return result; 16 } 17 sort(intervals.begin(), intervals.end(), 18 [] (const Interval& I1, const Interval& I2) 19 {return I1.start < I2.start; }); 20 int left = intervals[0].start, right = intervals[0].end; 21 for (int i = 1; i < intervals.size(); ++i) { 22 if (intervals[i].start <= right) { 23 right = max(right,intervals[i].end); 24 } 25 else { 26 result.push_back(Interval(left,right)); 27 left = intervals[i].start; 28 right = intervals[i].end; 29 } 30 } 31 result.push_back(Interval(left,right)); 32 return result; 33 } 34 };