classSolution { public: boolisCovered(vector<vector<int>>& ranges, int left, int right){ vector<int> diff(52, 0); // 差分数组 for (auto&& range: ranges) { ++diff[range[0]]; --diff[range[1]+1]; } // 前缀和 int curr = 0; for (int i = 1; i <= 50; ++i) { curr += diff[i]; if (i >= left && i <= right && curr <= 0) { returnfalse; } } returntrue; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { publicbooleanisCovered(int[][] ranges, int left, int right) { int[] diff = newint[52]; // 差分数组 for (int[] range : ranges) { ++diff[range[0]]; --diff[range[1] + 1]; } // 前缀和 intcurr=0; for (inti=1; i <= 50; ++i) { curr += diff[i]; if (i >= left && i <= right && curr <= 0) { returnfalse; } } returntrue; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclassSolution { publicboolIsCovered(int[][] ranges, int left, int right) { int[] diff = newint[52]; // 差分数组 foreach (int[] range in ranges) { ++diff[range[0]]; --diff[range[1] + 1]; } // 前缀和 int curr = 0; for (int i = 1; i <= 50; ++i) { curr += diff[i]; if (i >= left && i <= right && curr <= 0) { returnfalse; } } returntrue; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defisCovered(self, ranges: List[List[int]], left: int, right: int) -> bool: diff = [0] * 52# 差分数组 for l, r in ranges: diff[l] += 1 diff[r+1] -= 1 # 前缀和 curr = 0 for i inrange(1, 51): curr += diff[i] if left <= i <= right and curr <= 0: returnFalse returnTrue
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var isCovered = function(ranges, left, right) { const diff = newArray(52).fill(0); // 差分数组 for (const [l, r] of ranges) { diff[l]++; diff[r + 1]--; } // 前缀和 let curr = 0; for (let i = 1; i < 51; i++) { curr += diff[i]; if (left <= i && i <= right && curr <= 0) { returnfalse; } } returntrue; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcisCovered(ranges [][]int, left, right int)bool { diff := [52]int{} // 差分数组 for _, r := range ranges { diff[r[0]]++ diff[r[1]+1]-- } cnt := 0// 前缀和 for i := 1; i <= 50; i++ { cnt += diff[i] if cnt <= 0 && left <= i && i <= right { returnfalse } } returntrue }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
boolisCovered(int** ranges, int rangesSize, int* rangesColSize, int left, int right) { int diff[52]; // 差分数组 memset(diff, 0, sizeof(diff)); for (int i = 0; i < rangesSize; i++) { ++diff[ranges[i][0]]; --diff[ranges[i][1] + 1]; } // 前缀和 int curr = 0; for (int i = 1; i <= 50; ++i) { curr += diff[i]; if (i >= left && i <= right && curr <= 0) { returnfalse; } } returntrue; }