您的位置:首页 > 移动开发

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;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: