Skip to content

Latest commit

 

History

History
144 lines (111 loc) · 3.65 KB

File metadata and controls

144 lines (111 loc) · 3.65 KB

English Version

题目描述

给你一个二维整数数组 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

解法

利用差分数组进行区间更新

Python3

class Solution:
    def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
        diff = [0 for i in range(52)]
        for rg in ranges:
            diff[rg[0]] += 1
            diff[rg[1] + 1] -= 1
        cur = 0
        for i, df in enumerate(diff):
            cur += df
            if left <= i <= right and cur == 0:
                return False
        return True

Java

class Solution {
    public boolean isCovered(int[][] ranges, int left, int right) {
        int[] diff = new int[52];
        for (int[] range : ranges) {
            diff[range[0]]++;
            diff[range[1] + 1]--;
        }
        int cur = 0;
        for (int i = 0; i < 52; i++) {
            cur += diff[i];
            if (left <= i && i <= right && cur == 0) {
                return false;
            }
        }
        return true;
    }
}

TypeScript

function isCovered(ranges: number[][], left: number, right: number): boolean {
    let diff = new Array(52).fill(0);
    for (let [start, end] of ranges) {
        ++diff[start];
        --diff[end + 1];
    }
    let cur = 0;
    for (let i = 1; i <= 50; i++) {
        cur += diff[i];
        if (i >= left && i <= right && cur <= 0) {
            return false;
        }
    }
    return true;
};

Go

func isCovered(ranges [][]int, left int, right int) bool {
	diff := make([]int, 52)
	for _, rg := range ranges {
		diff[rg[0]]++
		diff[rg[1]+1]--
	}
	cur := 0
	for i, df := range diff {
		cur += df
		if i >= left && i <= right && cur == 0 {
			return false
		}
	}
	return true
}

...