algorithm-base/animation-simulation/数据结构和算法/翻转对.md

98 lines
4.2 KiB
Java
Raw Normal View History

2021-03-20 08:44:27 +00:00
#### [leetcode 493 ](https://leetcode-cn.com/problems/reverse-pairs/)
2021-03-20 07:58:25 +00:00
2021-03-20 08:30:29 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 07:58:25 +00:00
****
nums i < j nums[i] > 2*nums[j] (i, j)
1:
> : [1,3,2,3,1]
> : 2
2:
> : [2,4,3,5,1]
> : 3
****
![](https://cdn.jsdelivr.net/gh/tan45du/test1@master/20210122/微信截图_20210214121010.50g9z0xgda80.png)
6 > 2 * 2 6 count += mid - temp1 + 1
![](https://cdn.jsdelivr.net/gh/tan45du/test1@master/20210122/微信截图_20210214121711.77crljdzra00.png)
6 = 3 * 2
![](https://img-blog.csdnimg.cn/20210317192545806.gif#pic_center)
```java
class Solution {
private int count;
public int reversePairs(int[] nums) {
count = 0;
merge(nums, 0, nums.length - 1);
return count;
}
public void merge(int[] nums, int left, int right) {
if (left < right) {
int mid = left + ((right - left) >> 1);
merge(nums, left, mid);
merge(nums, mid + 1, right);
mergeSort(nums, left, mid, right);
}
}
public void mergeSort(int[] nums, int left, int mid, int right) {
int[] temparr = new int[right - left + 1];
int temp1 = left, temp2 = mid + 1, index = 0;
//计算翻转对
while (temp1 <= mid && temp2 <= right) {
//这里需要防止溢出
if (nums[temp1] > 2 * (long) nums[temp2]) {
count += mid - temp1 + 1;
temp2++;
} else {
temp1++;
}
}
//记得归位,我们还要继续使用
temp1 = left;
temp2 = mid + 1;
//归并排序
while (temp1 <= mid && temp2 <= right) {
if (nums[temp1] <= nums[temp2]) {
temparr[index++] = nums[temp1++];
} else {
temparr[index++] = nums[temp2++];
}
}
//照旧
if (temp1 <= mid) System.arraycopy(nums, temp1, temparr, index, mid - temp1 + 1);
if (temp2 <= right) System.arraycopy(nums, temp2, temparr, index, right - temp2 + 1);
System.arraycopy(temparr, 0, nums, left, right - left + 1);
}
}
```