Leetcode 1288. Remove Covered In
2021-08-13 本文已影响0人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Remove Covered Intervals2. Solution
解析:Version 1,先排序,先根据左侧排序,左侧相等再根据右侧排序,排序后相邻元素的左侧一定是非递减的。遍历相邻两个元素,有两种可能,要不左边包含右边,要不右边包含左边,如果满足条件,则移除对应元素,索引位置不变,不满足上述两种情况,则说明后一个元素的左侧及右侧都大于当前元素,索引加1
,继续比较。
- Version 1
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: (x[0], x[1]))
i = 0
while i < len(intervals) - 1:
if intervals[i][1] >= intervals[i+1][1]:
intervals.pop(i+1)
elif intervals[i][0] == intervals[i+1][0]:
intervals.pop(i)
else:
i += 1
return len(intervals)