[Leetcode] 56. Merge Intervals 解题报告
2017-01-15 00:49
417 查看
题目:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given
return
思路:
首先对区间进行排序,然后线性扫描:如果当前区间和上一个区间有重合,则和上一个区间合并,否则就新添加一个区间。时间复杂度为O(nlogn)(注意总体时间复杂度是排序的复杂度,而对排好序的区间进行合并的复杂度为O(n))。空间复杂度为O(1)。
代码:
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].
思路:
首先对区间进行排序,然后线性扫描:如果当前区间和上一个区间有重合,则和上一个区间合并,否则就新添加一个区间。时间复杂度为O(nlogn)(注意总体时间复杂度是排序的复杂度,而对排好序的区间进行合并的复杂度为O(n))。空间复杂度为O(1)。
代码:
/** * 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 Solution { public: vector<Interval> merge(vector<Interval>& intervals) { vector<Interval> result; if(intervals.empty()) return result; sort(intervals.begin(), intervals.end(), comp); result.push_back(intervals[0]); for(int i = 1; i < intervals.size();++i) { if(intervals[i].start <= result.back().end) result.back().end = max(result.back().end, intervals[i].end); else result.push_back(intervals[i]); } return result; } private: static bool comp(const Interval& a, const Interval& b) { if(a.start < b.start) return true; else if(a.start > b.start) return false; else return a.end < b.end; } };
相关文章推荐
- LeetCode 216. Combination Sum III 解题报告
- [Leetcode] 316. Remove Duplicate Letters 解题报告
- [Leetcode] 320. Generalized Abbreviation 解题报告
- [Leetcode] 649. Dota2 Senate 解题报告
- 【LeetCode】Word Break II 解题报告
- [leetcode] 163. Missing Ranges 解题报告
- 【LeetCode】 Add Digits 解题报告
- leetcode 40. Combination Sum II 解题报告
- [Leetcode] 488. Zuma Game 解题报告
- LeetCode解题报告--Search Insert Position
- 【LeetCode】695. Max Area of Island 解题报告
- [LeetCode]Nth Highest Salary,解题报告
- LeetCode解题报告--Reverse Nodes in k-Group
- Group Anagrams LeetCode 解题报告
- 【LeetCode】463.Island Perimeter(easy)解题报告
- [Leetcode] 665. Non-decreasing Array 解题报告
- [Leetcode] 666. Path Sum IV 解题报告
- 【LeetCode】Find Minimum in Rotated Sorted Array 解题报告
- leetcode第四周解题报告
- LeetCode 338.Counting Bits 解题报告