[Leetcode 84] 56 Merge Intervals
2013-07-24 13:13
375 查看
Problem:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given
return
Analysis:
First sort the vector according to the start time of each interval. Then scan through the vector, if the current interval's start time is between the former interval's strart and end time, we need to merge them. The newly merged interval's start is the former interval's start, but the end should be the max{current.end, former.end}.
To speed up this process, use an extra result vector to store the final result rather than using vector.erase method on original method.
Code:
View Code
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].
Analysis:
First sort the vector according to the start time of each interval. Then scan through the vector, if the current interval's start time is between the former interval's strart and end time, we need to merge them. The newly merged interval's start is the former interval's start, but the end should be the max{current.end, former.end}.
To speed up this process, use an extra result vector to store the final result rather than using vector.erase method on original method.
Code:
/** * 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 cmpA(const Interval& a, const Interval& b) { return a.start < b.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { // Start typing your C/C++ solution below // DO NOT write int main() vector<Interval> res; sort(intervals.begin(), intervals.end(), cmpA); Interval tmp = intervals[0]; for (int i=1; i<intervals.size(); i++) { if (tmp.start <= intervals[i].start && tmp.end >= intervals[i].start) { tmp.end = max(intervals[i].end, tmp.end); } else { res.push_back(tmp); tmp = intervals[i]; } } return res; } int max(int a, int b) { return (a>b)? a : b; } };
View Code
相关文章推荐
- leetCode 56, Merge Intervals
- [Leetcode] #56 Merge Intervals
- [leetcode 56] Merge Intervals
- leetcode(56). Merge Intervals
- LeetCode56——Merge Intervals
- LeetCode 56 Merge Intervals--In C++
- leetcode 56: Merge Intervals
- Leetcode 56 Merge Intervals
- leetcode || 56、 Merge Intervals
- leetcode[56]Merge Intervals
- LeetCode 56 Merge Intervals
- LeetCode - 56 - Merge Intervals
- LeetCode_OJ【56】Merge Intervals
- [Leetcode 56, Hard] Merge intervals
- LeetCode-56-Merge Intervals(C语言实现)
- 【leetcode】Array—— Merge Intervals(56)
- LeetCode(56)Merge Intervals
- [Java]leetcode56 Merge Intervals
- LeetCode 56 Merge Intervals
- LeetCode-56-Merge Intervals Python自定义sort,贪心