You are given a 2D integer array ranges
and two integers left
and right
. Each ranges[i] = [starti, endi]
represents an inclusive interval between starti
and endi
.
Return true
if each integer in the inclusive range [left, right]
is covered by at least one interval in ranges
. Return false
otherwise.
An integer x
is covered by an interval ranges[i] = [starti, endi]
if starti <= x <= endi
.
Example 1:
Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5 Output: true Explanation: Every integer between 2 and 5 is covered: - 2 is covered by the first range. - 3 and 4 are covered by the second range. - 5 is covered by the third range.
Example 2:
Input: ranges = [[1,10],[10,20]], left = 21, right = 21 Output: false Explanation: 21 is not covered by any range.
Constraints:
1 <= ranges.length <= 50
1 <= starti <= endi <= 50
1 <= left <= right <= 50
Companies:
Bloomberg
Related Topics:
Greedy
// OJ: https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
bool isCovered(vector<vector<int>>& A, int left, int right) {
unordered_set<int> s;
for (auto &v : A) {
for (int i = max(left,v[0]); i <= min(right,v[1]); ++i) {
s.insert(i);
}
}
return s.size() == right - left + 1;
}
};
// OJ: https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
bool isCovered(vector<vector<int>>& A, int left, int right) {
sort(begin(A), end(A));
if (A[0][0] > left) return false;
int i = 0, j = A[0][0];
while (i < A.size()) {
if (j < A[i][0] - 1) return false;
j = max(j, A[i][1]);
++i;
if (j >= right) return true;
}
return false;
}
};