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
| // @lc code=start
impl Solution {
/// ## 解题思路
/// - 归并排序
pub fn reverse_pairs(nums: Vec<i32>) -> i32 {
fn merge_sort_count(nums: &mut [i32], left: usize, right: usize, count: &mut i32) {
if left >= right - 1 {
return;
}
let mid = (left + right) >> 1;
merge_sort_count(nums, left, mid, count);
merge_sort_count(nums, mid, right, count);
let (mut l, mut r) = (left, mid);
for l in left..mid {
while r < right && (nums[l] as i64) <= (nums[r] as i64) * 2 {
r += 1;
}
if r < right && (nums[l] as i64) > (nums[r] as i64) * 2 {
*count += (right - r) as i32
}
}
let l_nums = nums[left..mid].to_vec();
let r_nums = nums[mid..right].to_vec();
let (mut l, mut r) = (0, 0);
let mut i = left;
while l < l_nums.len() && r < r_nums.len() {
if l_nums[l] as i64 >= r_nums[r] as i64 {
nums[i] = l_nums[l];
l += 1;
} else {
nums[i] = r_nums[r];
r += 1;
}
i += 1;
}
while l < l_nums.len() {
nums[i] = l_nums[l];
l += 1;
i += 1;
}
while r < r_nums.len() {
nums[i] = r_nums[r];
r += 1;
i += 1;
}
}
let n = nums.len();
let mut nums = nums;
let mut count = 0;
merge_sort_count(&mut nums, 0, n, &mut count);
count
}
}
// @lc code=end
|