-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
47 lines (43 loc) · 1.06 KB
/
Solution.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
class BinaryIndexedTree {
public:
int n;
vector<int> c;
BinaryIndexedTree(int _n)
: n(_n)
, c(_n + 1) {}
void update(int x, int delta) {
for (; x <= n; x += x & -x) {
c[x] += delta;
}
}
int query(int x) {
int s = 0;
for (; x; x -= x & -x) {
s += c[x];
}
return s;
}
};
class Solution {
public:
int kEmptySlots(vector<int>& bulbs, int k) {
int n = bulbs.size();
BinaryIndexedTree* tree = new BinaryIndexedTree(n);
bool vis[n + 1];
memset(vis, false, sizeof(vis));
for (int i = 1; i <= n; ++i) {
int x = bulbs[i - 1];
tree->update(x, 1);
vis[x] = true;
int y = x - k - 1;
if (y > 0 && vis[y] && tree->query(x - 1) - tree->query(y) == 0) {
return i;
}
y = x + k + 1;
if (y <= n && vis[y] && tree->query(y - 1) - tree->query(x) == 0) {
return i;
}
}
return -1;
}
};