-
Notifications
You must be signed in to change notification settings - Fork 14
/
Solution775.java
54 lines (42 loc) · 1.32 KB
/
Solution775.java
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
package leetcode.binaryindexedtree;
public class Solution775 {
public static void main(String[] args) {
System.out.println(new Solution775().isIdealPermutation(new int[]{1, 0, 2}));
}
public boolean isIdealPermutation(int[] nums) {
BinaryIndexedTree tree = new BinaryIndexedTree(nums.length);
int all = 0, local = 0;
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i - 1] > nums[i]) {
local++;
}
all += tree.query(nums[i] + 1, nums.length);
tree.update(nums[i] + 1, 1);
}
return all == local;
}
static class BinaryIndexedTree {
int[] tree;
public BinaryIndexedTree(int n) {
this.tree = new int[n + 1];
}
public int query(int left, int right) {
return query(right) - query(left - 1);
}
public int query(int index) {
int res = 0;
for (int i = index; i > 0; i -= lowbit(i)) {
res += tree[i];
}
return res;
}
public void update(int index, int val) {
for (int i = index; i < tree.length; i += lowbit(i)) {
tree[i] += val;
}
}
private int lowbit(int i) {
return i & -i;
}
}
}