leetcode——Non-overlapping Intervals
2016-11-03 23:55
330 查看
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Example 1:
Example 2:
Example 3:
解析:利用贪心算法求解,假设在某个区域,有n个区间重叠,则显然n个区间最后只能留下一个,而根据局部最优,势必留下end最小的最有利。根据这个思路,事先将数组排序,然后不断删去区间即可,时间复杂度为O(n).
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ] Output: 1 Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [ [1,2], [1,2], [1,2] ] Output: 2 Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [ [1,2], [2,3] ] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
解析:利用贪心算法求解,假设在某个区域,有n个区间重叠,则显然n个区间最后只能留下一个,而根据局部最优,势必留下end最小的最有利。根据这个思路,事先将数组排序,然后不断删去区间即可,时间复杂度为O(n).
class Solution { public: static bool cmp(Interval& a, Interval& b) { return a.end < b.end; } int eraseOverlapIntervals(vector<Interval>& intervals) { if(!intervals.size()) return 0; int num = 0; sort(intervals.begin(), intervals.end(), cmp); for(vector<Interval>::iterator i = intervals.begin(); i!=intervals.end(); i++) while(i != intervals.end()-1 && i->end > (i+1)->start) { intervals.erase(i+1); num ++; } return num; } };不懂为嘛,用迭代器写的反而耗时更长。。
相关文章推荐
- [LeetCode] DP 之 Maximum sum of 3 Non-Overlapping Subarrays
- LeetCode-Easy-Java-Non-decreasing Array
- Leetcode 600 Non-negative Integers without Consecutive Ones
- LeetCode:Non-decreasing Array - 非减数列
- LeetCode-665 Non-decreasing Array
- (dp)LeetCode Weekly Contest 34 -Non-negative Integers without Consecutive Ones
- LeetCode-665:Non-decreasing Array (判断是否为非递减数组)
- LeetCode | 689. Maximum Sum of 3 Non-Overlapping Subarrays 困难DP题分析与解答
- 【leetCode】control reaches end of non-void function [-Werror=return-type]
- leetcode 665 Non-decreasing Array
- [LeetCode] 689. Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和
- 20170401-leetcode-435-Non-overlapping Intervals
- leetCode:Non-overlapping Intervals
- leetcode-Non-decreasing Array
- Wildcard Matching (Recursive and Non Recursive method) (Leetcode 网易有道面试题)
- LeetCode 689 Maximum Sum of 3 Non-Overlapping Subarrays
- [LeetCode] Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和
- [LeetCode] Non-decreasing Array 非递减数列
- Leetcode之Non-decreasing Array 问题
- leetcode 689. Maximum Sum of 3 Non-Overlapping Subarrays 3个连续子数组最大和+动态规划DP