LeetCode C++ 435. Non-overlapping Intervals【贪心/排序/动态规划】中等

本文介绍了一种解决区间重叠问题的贪心算法,通过实例演示如何按区间右端点排序并移除最少数量的区间,使得剩余区间互不重叠。高效的代码实现和时间复杂度分析有助于理解该问题的解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

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.

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.

题意:给出一个区间集合,移除最少数量的区间,使得剩余区间不重合。


解法 贪心

本题等同于——最多保留多少个区间,让它们之间互相不重叠。关键是按照区间右端点从小到大来进行排序。具体代码如下:

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] ? a[1] < b[1] : a[0] < b[0];
        });
        int nonOverlapping = 0, n = intervals.size(), end = INT_MIN;
        for (int i = 0; i < n; ++i) {
            if (intervals[i][0] >= end) {
                ++nonOverlapping;
                end = intervals[i][1]; 
            } 
        }
        return n - nonOverlapping;
    }
};

运行效率如下:

执行用时:32 ms, 在所有 C++ 提交中击败了69.63% 的用户
内存消耗:9.3 MB, 在所有 C++ 提交中击败了78.73% 的用户
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值