检查是否区域内所有整数都被覆盖
题目描述:
给你一个二维数组ranges和两个整数left和right。每个ranges[i] = [starti, endi]表示一个从starti到endi的闭区间。
如果闭区间[left, right]内每个整数都被ranges中至少一个区间覆盖,那么请你返回true,否则返回false。
已知区间ranges[i] = [starti, endi],如果整数x满足starti <= x <= endi,那么我们称整数x被覆盖了。
示例1:
输入:ranges = [[1, 2], [3, 4], [5, 6]], left = 2, right = 5
输出:true
解释:2到5的每个整数都被覆盖了:2被第一个区间覆盖,3和4被第二个区间覆盖,5被第三个区间覆盖。
示例2:
输入:ranges = [[1, 10], [10, 20]], left = 21, right = 21
输出:false
解释:21没有被任何一个区间覆盖
提示:
- 1 <= ranges.length <= 50
- 1 <= starti <= endi <= 50
- 1 <= left <= right <= 50
思路:暴力法、差分、并查集
python代码:
暴力解法
暴力解法优化
差分
并查集
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
# 暴力法
# return all(any(l <= i <= r for l, r in ranges) for i in range(left, right+1))
# 暴力法优化
# covers = set()
# for l, r in ranges:
# covers.update({i for i in range(l, r+1)})
# return all(i in covers for i in range(left, right+1))
# 差分
# diff = defaultdict(int)
# for l, r in ranges:
# diff[l] += 1
# diff[r+1] -= 1
# cur = 0
# for i in range(1, right+1):
# cur += diff[i]
# if cur <= 0 and left <= i:
# return False
# return True
# 并查集
f = [i for i in range(52)]
def find(x):
return x if f[x] == x else find(f[x])
def union(x, y):
f[find(x)] = find(y)
for l, r in ranges:
for i in range(l, r+1):
union(i, r+1)
return find(left) > right