forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.go
53 lines (49 loc) · 931 Bytes
/
Solution2.go
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
type BinaryIndexedTree struct {
n int
c []int
}
func newBinaryIndexedTree(n int) *BinaryIndexedTree {
c := make([]int, n+1)
return &BinaryIndexedTree{n, c}
}
func (this *BinaryIndexedTree) update(x, val int) {
for x <= this.n {
this.c[x] += val
x += x & -x
}
}
func (this *BinaryIndexedTree) query(x int) int {
s := 0
for x > 0 {
s += this.c[x]
x -= x & -x
}
return s
}
func find132pattern(nums []int) bool {
n := len(nums)
s := make([]int, n)
left := make([]int, n+1)
left[0] = 1 << 30
copy(s, nums)
sort.Ints(s)
m := 0
for i := 0; i < n; i++ {
left[i+1] = min(left[i], nums[i])
if i == 0 || s[i] != s[i-1] {
s[m] = s[i]
m++
}
}
s = s[:m]
tree := newBinaryIndexedTree(m)
for i := n - 1; i >= 0; i-- {
x := sort.SearchInts(s, nums[i]) + 1
y := sort.SearchInts(s, left[i]) + 1
if x > y && tree.query(x-1) > tree.query(y) {
return true
}
tree.update(x, 1)
}
return false
}