forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cpp
41 lines (37 loc) · 815 Bytes
/
Solution2.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
class BinaryIndexedTree {
public:
BinaryIndexedTree(int _n)
: n(_n)
, c(_n + 1) {}
void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += x & -x;
}
}
int query(int x) {
int s = 0;
while (x) {
s += c[x];
x -= x & -x;
}
return s;
}
private:
int n;
vector<int> c;
};
class Solution {
public:
bool isIdealPermutation(vector<int>& nums) {
int n = nums.size();
BinaryIndexedTree tree(n);
long cnt = 0;
for (int i = 0; i < n && ~cnt; ++i) {
cnt += (i < n - 1 && nums[i] > nums[i + 1]);
cnt -= (i - tree.query(nums[i]));
tree.update(nums[i] + 1, 1);
}
return cnt == 0;
}
};