leetcode——Non-overlapping Intervals
来源:互联网 发布:ubuntu翻译软件 编辑:程序博客网 时间:2024/06/05 22:34
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:
Input: [ [1,2], [2,3], [3,4], [1,3] ]Output: 1Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [ [1,2], [1,2], [1,2] ]Output: 2Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [ [1,2], [2,3] ]Output: 0Explanation: 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;}};不懂为嘛,用迭代器写的反而耗时更长。。
0 0
- leetcode——Non-overlapping Intervals
- leetCode:Non-overlapping Intervals
- Leetcode——134. Gas Station && 435. Non-overlapping Intervals
- LeetCode 435. Non-overlapping Intervals
- leetcode 435. Non-overlapping Intervals
- [Leetcode] 435. Non-overlapping Intervals
- 【LeetCode】 435. Non-overlapping Intervals
- Leetcode 435. Non-overlapping Intervals
- LeetCode 435. Non-overlapping Intervals
- [leetcode]435. Non-overlapping Intervals
- leetcode-435. Non-overlapping Intervals
- [LeetCode]435. Non-overlapping Intervals
- Leetcode 435. Non-overlapping Intervals
- LeetCode 435 Non-overlapping Intervals
- LeetCode 435. Non-overlapping Intervals
- LeetCode 435. Non-overlapping Intervals
- 【LeetCode】435. Non-overlapping Intervals
- LeetCode 435. Non-overlapping Intervals
- Eclipse的SonarLint插件概述
- 关于redis中使用锁机制,( 实现分布式锁和任务队列)
- udp 学习
- 微信小程序7---image组件
- 二叉搜索树(BST)的删除算法原理解析
- leetcode——Non-overlapping Intervals
- http协议
- 16年11月03问题汇总
- Shiro在Spring中的缓存配置
- 1.js判断浏览器版本或类型
- nginx配置:反向代理 负载均衡 后端健康检查 缓存
- Activity跳转的几种方式
- onKeyDown事件,设置按返回键间隔不超过两秒时退出程序问题
- hdu 1050