美文网首页
leetcode435.Non-overlapping Inte

leetcode435.Non-overlapping Inte

作者: 就是果味熊 | 来源:发表于2020-06-29 15:53 被阅读0次

    原题链接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 Inte

          本文链接:https://www.haomeiwen.com/subject/kwoofktx.html