LeetCode 435. Non-overlapping Intervals 无重叠区间(贪心问题,两种解法)
2019-06-14 17:31
2081 查看
LeetCode 435. Non-overlapping Intervals 无重叠区间
435. Non-overlapping Intervals 无重叠区间
题目描述
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: 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.
解答1
这道题和用最少数量的箭引爆气球类似,都是贪心算法。
第一种思路,我们可以先按照interval的右坐标进行从小到大排序。然后从第二个interval开始,每当第二个interval的左坐标小于第一个interval的右坐标,我们令count++。
代码1
class Solution { public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { if (intervals.empty()) return 0; sort(intervals.begin(), intervals.end(),[&](const vector<int >&a, const vector<int> &b){return a[1] < b[1];}); //本来count应该初始化为0,但是因为底下的for循环,又把intervals[0][1]考虑了一遍 //所以这里count 初始化为0 - 1 auto count = -1; auto lastPoint = intervals[0][1]; for (auto & i : intervals) { if (i[0] < lastPoint) { count++; if (i[1] < lastPoint) lastPoint = i[1]; } else lastPoint = i[1]; } return count; } };
解答1
第二种思路,找到需要去掉的最少interval的数量,就是总数量减去不重叠interval的数量。
代码如下。
代码1
class Solution { public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { if (intervals.empty()) return 0; sort(intervals.begin(), intervals.end(),[&](const vector<int >&a, const vector<int> &b){return a[1] < b[1];}); auto count = 1; auto lastPoint = intervals[0][1]; for (auto & i : intervals) { if (i[0] >= lastPoint) { count++; lastPoint = i[1]; } } return intervals.size() - count; } };
相关文章推荐
- 会场安排问题(南阳oj14)(贪心-区间不重叠)
- ※ Leetcode - Segment Tree - 307. Range Sum Query - Mutable (线段树+树状数组两种解法以及模板的常见问题解析)
- POJ-5353-Fence Repair(哈夫曼问题->贪心(一种解法两种做法))
- 区间重叠问题 (贪心)
- 教室课程调度问题的两种解法(区间着色问题)
- POJ 2376 浅谈一类区间覆盖问题的贪心解法
- Moving Tables(杭电1050)(贪心---区间不重叠问题)
- 质数环问题的两种解法及优化思路
- leetcode 315. Count of Smaller Numbers After Self 两种思路(欢迎探讨更优解法)
- C++实现&nbsp;贪心算法-区间覆盖问题
- POJ1328-贪心-区间选点问题
- UVA 10382 Watering Grass (贪心 + 区间覆盖问题)
- Radar Installation(poj1328,贪心,区间交集问题)
- 贪心-区间调度问题
- POJ 1328 Radar Installation【贪心 区间问题】
- 活动选择问题的动归和贪心解法
- 最长公共子序列(LCS)问题(非连续子序列)的两种解法
- UVa 1615 Highway (贪心,区间选点问题)
- 初入算法篇(贪心) 最多不相交区间问题HDU2037+FOJ1230
- LeetCode76 Minimum Window Substring(两种解法)