-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution2.ts
64 lines (59 loc) · 1.42 KB
/
Solution2.ts
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
class BinaryIndextedTree {
n: number;
c: number[];
constructor(n: number) {
this.n = n;
this.c = new Array(n + 1).fill(0);
}
update(x: number, val: number): void {
while (x <= this.n) {
this.c[x] += val;
x += x & -x;
}
}
query(x: number): number {
let s = 0;
while (x) {
s += this.c[x];
x -= x & -x;
}
return s;
}
}
function find132pattern(nums: number[]): boolean {
let s: number[] = [...nums];
s.sort((a, b) => a - b);
const n = nums.length;
const left: number[] = new Array(n + 1).fill(1 << 30);
let m = 0;
for (let 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];
}
}
s = s.slice(0, m);
const tree = new BinaryIndextedTree(m);
for (let i = n - 1; i >= 0; --i) {
const x = search(s, nums[i]);
const y = search(s, left[i]);
if (x > y && tree.query(x - 1) > tree.query(y)) {
return true;
}
tree.update(x, 1);
}
return false;
}
function search(nums: number[], x: number): number {
let l = 0,
r = nums.length - 1;
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l + 1;
}