【LeetCode】435. 无重叠区间 解题报告 (python)

原题地址:https://leetcode-cn.com/problems/non-overlapping-intervals/submissions/

题目描述:

给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。

注意:

可以认为区间的终点总是大于它的起点。
区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。
示例 1:

输入: [ [1,2], [2,3], [3,4], [1,3] ]

输出: 1

解释: 移除 [1,3] 后,剩下的区间没有重叠。
示例 2:

输入: [ [1,2], [1,2], [1,2] ]

输出: 2

解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
示例 3:

输入: [ [1,2], [2,3] ]

输出: 0

 

解题方案:

贪心算法,首先对数列排序,再选尾数最小的数组:

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        if len(intervals) == 0:
            return 0
        intervals.sort()
        start = intervals[0][0]
        end = intervals[0][1]
        res = 0
        for i in range(1, len(intervals)):
            end = min(end, intervals[i][1])
            if end > intervals[i][0]:
                res += 1
            else:
                end = intervals[i][1]
        return res
class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        size = len(intervals)
        if size <= 1:
        	return 0
        count = 1
        def find2(nums):
        	return nums[1]
        intervals.sort(key=find2)

        end = intervals[0][1]
        for i in range(1, size):
        	if intervals[i][0] >= end:
        		count += 1
        		end = intervals[i][1]
        return size-count
class Solution:
    def eraseOverlapIntervals(self,intervals):
        end, cnt = float('-inf'), 0
        for i in sorted(intervals, key=lambda x: x[1]):
            if i[0] >= end:
                end = i[1]
            else:
                cnt += 1
        return cnt
class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        if not intervals:
            return 0
        res = 1
        intervals.sort(key=lambda x:x[1])
        end = intervals[0][1]
        for index in range(1,len(intervals)):
            if intervals[index][0]

 

你可能感兴趣的:(LeetCode)