Leetcode Leetcode 435. Greedy without overlapping interval

Topic:

Given a set of intervals, find the minimum number of intervals that need to be removed so that the remaining intervals do not overlap each other.

note:

It can be considered that the end of an interval is always greater than its starting point.
The boundaries of the intervals [1,2] and [2,3] "touch" each other, but do not overlap each other.

Example 1:

Input: [[1,2], [2,3], [3,4], [1,3]]
Output: 1
Explanation: After removing [1,3], the remaining intervals do not overlap.

Example 2:

Input: [[1,2], [1,2], [1,2]]
Output: 2
Explanation: You need to remove two [1,2] so that the remaining intervals do not overlap.

Example 3:

Input: [[1,2], [2,3]]
Output: 0
Explanation: You do not need to remove any intervals, because they are already non-overlapping.

Idea:
First sort according to the right end of the interval
(the idea of sorting according to the left interval is similar, but a lot of judgments are needed), and
then start from the second smallest interval on the
right end. If the second smallest interval on the right end is still the smallest, the left end If the left end point of the right end point interval is small
, this interval needs to be deleted, and the number of intervals to be deleted res += 1
If the left end point is found to be greater than or equal to the right end point of the smallest right interval, the
new right end point of the interval is set as the new whole End point of the right interval
and so on, until all

The idea of ​​the greedy algorithm for this question is similar to that of leetcode 452. Use the least number of arrows to detonate the balloon and it is similar, for reference

452 problem solution link

Code:

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort(key=lambda x: x[1])
        res = 0
        
        if len(intervals) == 0:
            return 0
        
        i = 1
        a = 0
        while i < len(intervals):
            if intervals[a][1] > intervals[i][0]:
                res += 1
                i += 1
            else:
                a = i
                i += 1

        return res

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112130088