LeetCode 435 Non-overlapping Intervals (Python)

Posted by 小明MaxMing on August 15, 2020

题目

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

解题思路

贪心,先按区间左端点排序,遍历区间,如果遇到重叠的区间,留右端点小的

代码

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        if len(intervals) == 0:
            return 0
        intervals.sort()
        now = intervals[0][1]
        res = 0
        for i in intervals[1:]:
            if i[0] < now:
                now = min(i[1], now)
                res += 1
            else:
                now = i[1]
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅