码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode1287

时间:2019-12-15 11:02:28      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:pre   red   没有   ==   pytho   val   bsp   sel   tin   

 1 class Solution:
 2     def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
 3         #intervals = sorted(intervals)
 4         n = len(intervals)
 5         dp = [0] * n
 6         for i in range(n):
 7             if dp[i] == 1:
 8                 continue
 9             else:
10                 for j in range(i+1,n):
11                     if dp[j] == 1:
12                         continue
13                     else:
14                         if intervals[i][0] <= intervals[j][0] and intervals[i][1] >=intervals[j][1]:
15                             dp[j] = 1
16                         elif intervals[i][0] >= intervals[j][0] and intervals[i][1] <=intervals[j][1]:
17                             dp[i] = 1
18         count = 0
19         for i in range(n):
20             if dp[i] == 0:
21                 count += 1
22         return count

1288. Remove Covered Intervals

并查集思想,将可以被合并的(范围小的)区间标记,最后没有标记的就是所求的个数。

 

另一种思路,先排序再比较,效率更高:

 1 class Solution:
 2     def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
 3         count = len(intervals)
 4         intervals.sort()
 5         MAX = intervals[0][1]
 6         for i,(s,e) in enumerate(intervals[1:]):
 7             if e > MAX:
 8                 MAX = e
 9             else:
10                 count -= 1
11         return count

参考:https://leetcode.com/problems/remove-covered-intervals/discuss/451532/Python3-O(n*logn)-solution-with-sort

leetcode1287

标签:pre   red   没有   ==   pytho   val   bsp   sel   tin   

原文地址:https://www.cnblogs.com/asenyang/p/12041717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!