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
|
func reversePairs(nums []int) int {
n := len(nums)
tmp := make([]int, n)
var mergeSort func([]int, []int, int, int) int
mergeSort = func(nums, tmp []int, l, r int) int {
if l >= r {
return 0
}
mid := l + (r-l)/2
leftPairs := mergeSort(nums, tmp, l, mid)
rightPairs := mergeSort(nums, tmp, mid+1, r)
if nums[mid] <= nums[mid+1] {
return leftPairs + rightPairs
}
for i := l; i <= r; i++ {
tmp[i] = nums[i]
}
i, j, count := l, mid+1, 0
for k := l; k <= r; k++ {
// 左半部分已经遍历完
if i >= mid+1 {
nums[k] = tmp[j]
j++
} else if j > r { // 右半部分已遍历完
nums[k] = tmp[i]
i++
} else if tmp[i] <= tmp[j] {
nums[k] = tmp[i]
i++
} else {
nums[k] = tmp[j]
count += mid + 1 - i
j++
}
}
return count + leftPairs + rightPairs
}
return mergeSort(nums, tmp, 0, n-1)
}
|