博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】435. Non-overlapping Intervals
阅读量:6233 次
发布时间:2019-06-21

本文共 1737 字,大约阅读时间需要 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.

Note:

  1. You may assume the interval's end point is always bigger than its start point.
  2. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.

 

Example 1:

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

 

Example 2:

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

 

Example 3:

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

解题思路:本题可以用贪心算法。 首先对 intervals 按start从小到大排序,如果start相同,则按end从小到大。接下来遍历intervals,如果intervals相邻的两个元素有重叠,删除掉end较大的那个,最后intervals中留下来的元素都是不重叠的。

代码如下:

# Definition for an interval.# class Interval(object):#     def __init__(self, s=0, e=0):#         self.start = s#         self.end = eclass Solution(object):    def eraseOverlapIntervals(self, intervals):        """        :type intervals: List[Interval]        :rtype: int        """        def cmpf(i1,i2):            if i1.start != i2.start:                return i1.start - i2.start            return i1.end - i2.end        intervals.sort(cmp=cmpf)        keep = None        res = 0        while len(intervals) > 0:            item = intervals.pop(0)            if keep == None or keep.end <= item.start:                keep = item            elif keep.end <= item.end:                res += 1            elif keep.end > item.end:                keep = item                res += 1        return res

 

转载于:https://www.cnblogs.com/seyjs/p/10494587.html

你可能感兴趣的文章
spring的事务操作
查看>>
Extensions for Spatial Data
查看>>
Hadoop HDFS 用户指南
查看>>
primefaces 查询 点击按钮 加载 动画 ajax loader
查看>>
Java单例模式——并非看起来那么简单
查看>>
curl库pycurl实例及参数详解
查看>>
actor中!(tell)与forward的差别
查看>>
Android - Activity定制横屏(landscape)显示
查看>>
SQL中 EXCEPT、INTERSECT用法
查看>>
基于Token的WEB后台认证机制
查看>>
[Python] Reuse Code in Multiple Projects with Python Modules
查看>>
026——VUE中事件修饰符之使用$event与$prevent修饰符操作表单
查看>>
dynamic web module讲解
查看>>
C# 过滤特殊字符,保留中文,字母,数字,和-
查看>>
Pycharm安装详细教程
查看>>
WPF自定义LED风格数字显示控件
查看>>
Linux编译步骤概述
查看>>
Ubuntu环境使用apt命令下载管理包的优势
查看>>
如何利用MongoDB打造TOP榜小程序
查看>>
Eureka自我保护模式——难点重点
查看>>