forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck-if-all-the-integers-in-a-range-are-covered.cpp
60 lines (56 loc) · 1.44 KB
/
check-if-all-the-integers-in-a-range-are-covered.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Time: O(n + r)
// Space: O(r)
// if r is small, this is better
class Solution {
public:
bool isCovered(vector<vector<int>>& ranges, int left, int right) {
static const int RANGE_SIZE = 50;
vector<int> interval(RANGE_SIZE + 1);
for (const auto& r : ranges) {
++interval[r[0] - 1];
--interval[(r[1] - 1) + 1];
}
for (int i = 0, cnt = 0; i <= right - 1; ++i) {
cnt += interval[i];
if (i >= left - 1 && !cnt) {
return false;
}
}
return true;
}
};
// Time: O(nlogn)
// Space: O(1)
// if r is big, this is better
class Solution2 {
public:
bool isCovered(vector<vector<int>>& ranges, int left, int right) {
sort(begin(ranges), end(ranges));
for (const auto& r : ranges) {
if (r[0] <= left && left <= r[1]) {
left = r[1] + 1;
}
}
return left > right;
}
};
// Time: O(n * r)
// Space: O(1)
class Solution3 {
public:
bool isCovered(vector<vector<int>>& ranges, int left, int right) {
for (int i = left; i <= right; ++i) {
bool found = false;
for (const auto& r : ranges) {
if (r[0] <= i && i <= r[1]) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
};