435. Non-overlapping Intervals

435. Non-overlapping Intervals

Medium

3853111Add to ListShare

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Example 1:

Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.

Example 2:

Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.

Example 3:

Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

Constraints:

  • 1 <= intervals.length <= 105
  • intervals[i].length == 2
  • -5 * 104 <= starti < endi <= 5 * 104

自己的,不知为啥跑的时间挺长的?

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        """
        assert Solution().eraseOverlapIntervals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
        assert Solution().eraseOverlapIntervals([[1, 2], [1, 2], [1, 2]]) == 2
        assert Solution().eraseOverlapIntervals([[1, 2], [2, 3]]) == 0
        解体思路:区间[x,y]根据x,y排序后,从左边开始枚举,若出现相交,删除y较大的段,计数
        时间复杂度:O(nlogn),空间复杂度:O(1)
        """
        if intervals is None or len(intervals) <= 0:
            return 0

        # 自定义排序
        # def myCmp(a: List[int], b: List[int]) -> int:
        #     if a[0] == b[0]:
        #         if a[1] > b[1]:
        #             return 1
        #         elif a[1] < b[1]:
        #             return -1
        #         return 0
        #     return 1 if a[0] > b[0] else -1

        result = 0
        # from functools import cmp_to_key
        # intervals.sort(key=cmp_to_key(myCmp))
        intervals.sort()
        # print(intervals)

        last = intervals[0]
        for i in range(1, len(intervals)):
            if intervals[i][0] < last[1]:
                # 相交,取右边靠前的段,即y比较小的,为了不影响后面的
                result += 1
                last = intervals[i] if intervals[i][1] < last[1] else last
            else:
                last = intervals[i]

        return result

别人的:这里其实只要贪心选尾巴小的排序就行了,排序算法里会少些判断

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort(key=lambda x:x[1])
        prev = float("-inf")
        ans = 0
        for i in intervals:
            if i[0] >= prev:
                prev = i[1]
            else:
                ans += 1
        return ans

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值