-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathshortest-subarray-with-or-at-least-k-ii.cpp
45 lines (42 loc) · 1.33 KB
/
shortest-subarray-with-or-at-least-k-ii.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
// Time: O(nlogr) = O(n * 30)
// Space: O(logr) = O(30)
// freq table, two pointers
class Solution {
public:
int minimumSubarrayLength(vector<int>& nums, int k) {
const auto& bit_length = [](int x) {
return (x ? std::__lg(x) : -1) + 1;
};
const int total = accumulate(cbegin(nums), cend(nums), 0, [](const auto& x, const auto& y) {
return x | y;
});
if (total < k) {
return -1;
}
vector<int> cnt(bit_length(total));
const auto& update = [&](int x, int d, int curr) {
for (int i = 0; (1 << i) <= x; ++i) {
if (!(x & (1 << i))) {
continue;
}
if (cnt[i] == 0) {
curr ^= 1 << i;
}
cnt[i] += d;
if (cnt[i] == 0) {
curr ^= 1 << i;
}
}
return curr;
};
int result = size(nums);
for (int right = 0, left = 0, curr = 0; right < size(nums); ++right) {
curr = update(nums[right], +1, curr);
for (; left <= right && curr >= k; ++left) {
result = min(result, right - left + 1);
curr = update(nums[left], -1, curr);
}
}
return result;
}
};