leetcode435.Non-overlapping Intervals

原题链接https://leetcode.com/problems/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.

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.

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        if len(intervals) < 2:
            return 0
        intervals = sorted(intervals, key=lambda x: x[1])
        count, end = 0, float("-inf")
        
        for interval in intervals:
            if interval[0] >= end:
                end = interval[1]
            else:
                count += 1
        return count

对每个区间[l, r] 按照r的大小升序排列,遍历数组,初始化end=-inf 当当前元素的l值小于end值,说明当前区间与上一区间会重叠,count+1,若大于等于end值,说明不会重叠,更新end为当前区间的r值。遍历完返回count

你可能感兴趣的:(leetcode435.Non-overlapping Intervals)