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
并查集思想,将可以被合并的(范围小的)区间标记,最后没有标记的就是所求的个数。
另一种思路,先排序再比较,效率更高:
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