forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.java
65 lines (60 loc) · 1.49 KB
/
Solution2.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
55
56
57
58
59
60
61
62
63
64
65
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int v) {
while (x <= n) {
c[x] += v;
x += x & -x;
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= x & -x;
}
return s;
}
}
class Solution {
public boolean find132pattern(int[] nums) {
int[] s = nums.clone();
Arrays.sort(s);
int n = nums.length;
int m = 0;
int[] left = new int[n + 1];
left[0] = 1 << 30;
for (int i = 0; i < n; ++i) {
left[i + 1] = Math.min(left[i], nums[i]);
if (i == 0 || s[i] != s[i - 1]) {
s[m++] = s[i];
}
}
BinaryIndexedTree tree = new BinaryIndexedTree(m);
for (int i = n - 1; i >= 0; --i) {
int x = search(s, m, nums[i]);
int y = search(s, m, left[i]);
if (x > y && tree.query(x - 1) > tree.query(y)) {
return true;
}
tree.update(x, 1);
}
return false;
}
private int search(int[] nums, int r, int x) {
int l = 0;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l + 1;
}
}