首页 > 代码库 > LeetCode56 Merge Intervals

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 };

 

 

LeetCode56 Merge Intervals