-
Notifications
You must be signed in to change notification settings - Fork 0
/
493.go
128 lines (113 loc) · 2.16 KB
/
493.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package p493
import (
"sort"
)
/**
Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].
You need to return the number of important reverse pairs in the given array.
Example1:
Input: [1,3,2,3,1]
Output: 2
Example2:
Input: [2,4,3,5,1]
Output: 3
Note:
The length of the given array will not exceed 50,000.
All the numbers in the input array are in the range of 32-bit integer.
*/
type bstNode struct {
val int
sum int
left *bstNode
right *bstNode
}
func newNode(val int) *bstNode {
return &bstNode{
val: val,
sum: 1,
}
}
type bsTree struct {
root *bstNode
}
func (t *bsTree) Search(v int) int {
cnt := 0
node := t.root
for node != nil {
if node.val < v {
cnt += node.sum
node = node.right
} else {
node = node.left
}
}
return cnt
}
func (t *bsTree) Insert(v int) {
if t.root == nil {
t.root = newNode(v)
} else {
node := t.root
for {
if node.val < v {
if node.right == nil {
node.right = newNode(v)
break
} else {
node = node.right
}
} else if node.val > v {
node.sum++
if node.left == nil {
node.left = newNode(v)
break
} else {
node = node.left
}
} else {
node.sum++
break
}
}
}
}
func reversePairsSlow(nums []int) int {
res := 0
bst := bsTree{}
for i := len(nums) - 1; i >= 0; i-- {
res += bst.Search(nums[i])
bst.Insert(nums[i] * 2)
}
return res
}
func mergeSort(nums, helper []int, start, end int) int {
if start >= end {
return 0
}
mid := start + (end-start)/2
cnt := mergeSort(nums, helper, start, mid) + mergeSort(nums, helper, mid+1, end)
copy(helper, nums[start:mid+1])
ix, ls, rs := start, start, mid+1
offset := 0
for ix <= end {
if ls > mid || (rs <= end && helper[ls-start] >= nums[rs]) {
if start+offset <= mid {
find := sort.SearchInts(helper[offset:mid+1-start], nums[rs]*2+1)
cnt += mid + 1 - (start + offset) - find
offset += find
}
nums[ix] = nums[rs]
ix++
rs++
} else {
nums[ix] = helper[ls-start]
ix++
ls++
}
}
return cnt
}
func reversePairs(nums []int) int {
helper := make([]int, len(nums)/2+1)
return mergeSort(nums, helper, 0, len(nums)-1)
}