|
| 1 | +# LeetCode 435. Non-overlapping Intervals |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. |
| 6 | + |
| 7 | +Example 1: |
| 8 | + |
| 9 | +```py |
| 10 | +Input: [[1,2],[2,3],[3,4],[1,3]] |
| 11 | +Output: 1 |
| 12 | +Explanation: [1,3] can be removed and the rest of intervals are non-overlapping. |
| 13 | +``` |
| 14 | +Example 2: |
| 15 | + |
| 16 | +```py |
| 17 | +Input: [[1,2],[1,2],[1,2]] |
| 18 | +Output: 2 |
| 19 | +Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping. |
| 20 | +``` |
| 21 | +Example 3: |
| 22 | + |
| 23 | +```py |
| 24 | +Input: [[1,2],[2,3]] |
| 25 | +Output: 0 |
| 26 | +Explanation: You don't need to remove any of the intervals since they're already non-overlapping. |
| 27 | +``` |
| 28 | +Note: |
| 29 | + |
| 30 | +```py |
| 31 | +You may assume the interval's end point is always bigger than its start point. |
| 32 | +Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. |
| 33 | +``` |
| 34 | + |
| 35 | +### 思路 |
| 36 | + |
| 37 | +* 对每个区间按照起始位置从小到大排序。 |
| 38 | +* 对于两个区间,如果前一个区间的结尾位置大于后一个区间的起始位置,说明存在重叠,需要去除重复。 |
| 39 | +* 为了尽量减少去重的区间,我们选择去掉结尾位置靠后的区间。在实际的代码中,我们不需要真的删除区间,用一个变量指向上一个保留的区间就可以了。 |
| 40 | + |
| 41 | +```py |
| 42 | +# -*- coding: utf-8 -*- |
| 43 | +# @Author: 何睿 |
| 44 | +# @Create Date: 2020-03-31 19:18:41 |
| 45 | +# @Last Modified by: 何睿 |
| 46 | +# @Last Modified time: 2020-04-01 15:23:00 |
| 47 | +rom typing import List |
| 48 | + |
| 49 | + |
| 50 | +class Solution: |
| 51 | + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: |
| 52 | + intervals = sorted(intervals, key=lambda x: x[0]) |
| 53 | + count = 0 |
| 54 | + last = 0 |
| 55 | + for i in range(1, len(intervals)): |
| 56 | + # 上一个区间的 end 大于下一个区间的 start,说明有重叠 |
| 57 | + if intervals[last][1] > intervals[i][0]: |
| 58 | + count += 1 |
| 59 | + # 保留区间中 end 较小的那一个 |
| 60 | + if intervals[last][1] >= intervals[i][1]: |
| 61 | + last = i |
| 62 | + # 没有重叠,last 指向下一个区间 |
| 63 | + else: |
| 64 | + last = i |
| 65 | + |
| 66 | + return count |
| 67 | +``` |
| 68 | +源代码文件在 [这里](https://github.com/ruicore/Algorithm/blob/master/LeetCode/2020-03-31-435-Non-overlapping-Intervals.py) 。 |
| 69 | +©本文首发于 何睿的博客 ,欢迎转载,转载需保留 [文章来源](https://ruicore.cn/leetcode-435-non-overlapping-intervals/) ,作者信息和本声明. |
0 commit comments