Skip to content

Commit e03b8a7

Browse files
committed
1 parent e3eb326 commit e03b8a7

File tree

1 file changed

+58
-0
lines changed
  • src/main/kotlin/leetcode/shu-zu-zhong-de-ni-xu-dui-lcof

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package leetcode.`shu-zu-zhong-de-ni-xu-dui-lcof`
2+
3+
import org.junit.Test
4+
5+
// 太难了。。。写得头都要裂了才写出来
6+
class Solution {
7+
companion object {
8+
var count = 0
9+
}
10+
11+
fun reversePairs(nums: IntArray): Int {
12+
count =0
13+
if (nums.isEmpty()) return 0
14+
process(0, nums.lastIndex, nums)
15+
return count
16+
}
17+
18+
fun process(l: Int, r: Int, nums: IntArray): IntArray {
19+
if (!(l in nums.indices && r in nums.indices && l < r)) return intArrayOf(nums[l])
20+
val mid = l + ((r - l) shr 2)
21+
return merge(process(l, mid, nums), process(mid + 1, r, nums))
22+
}
23+
24+
fun merge(arrayL: IntArray, arrayR: IntArray): IntArray {
25+
val merge = IntArray(arrayL.size + arrayR.size)
26+
var pL = 0
27+
var pR = 0
28+
var index = 0
29+
while ((pL in arrayL.indices) && (pR in arrayR.indices)) {
30+
if (arrayL[pL] <= arrayR[pR]) {
31+
merge[index] = arrayL[pL]
32+
pL++
33+
} else {
34+
merge[index] = arrayR[pR]
35+
pR++
36+
count += (arrayL.size - pL)
37+
}
38+
index++
39+
}
40+
while (pL in arrayL.indices) {
41+
merge[index] = arrayL[pL]
42+
index++
43+
pL++
44+
}
45+
while (pR in arrayR.indices) {
46+
merge[index] = arrayR[pR]
47+
index++
48+
pR++
49+
}
50+
return merge
51+
}
52+
53+
@Test
54+
fun test() {
55+
val intArray = intArrayOf(2,4,3,5,1)
56+
println( reversePairs(intArray))
57+
}
58+
}

0 commit comments

Comments
 (0)