AcWing 65. 数组中的逆序对--java
原题链接
困难
作者:
gz227
,
2020-06-05 09:12:56
,
所有人可见
,
阅读 745
java,利用归并排序模板求解逆序对
//归并排序求逆序对
class Solution {
static int res;
public int inversePairs(int[] nums) {
mergeSort(nums, 0, nums.length - 1);
return res;
}
public void mergeSort(int[] nums, int l, int r) {
if(l >= r) return;
int mid = l + r >> 1;
mergeSort(nums, l, mid);
mergeSort(nums, mid + 1, r);
int k = 0;
int[] temp = new int[r - l + 1];
int i = l, j = mid + 1;
while(i <= mid && j <= r) {
if(nums[i] <= nums[j]) {
temp[k++] = nums[i++];
} else{
res += mid - i + 1;
temp[k++] = nums[j++];
}
}
while(i <= mid) temp[k++] = nums[i++];
while(j <= r) temp[k++] = nums[j++];
for(i = l, j = 0; i <= r; i++, j++) nums[i] = temp[j];
}
}