题目:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
限制:
0 <= 数组长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程:
思路来自LeetCode用户:因果.
归并排序
class Solution {
int count = 0;
public int reversePairs(int[] nums) {
this.count = 0;
sort(nums, 0, nums.length - 1,new int[nums.length]);
return count;
}
public void sort(int[] nums,int left,int right,int[] temp){
if(left < right){
int mid = left + (right - left) / 2;//开始递归划分
sort(nums,left,mid,temp);//归并排序左部分(left,mid)
sort(nums,mid+1,right,temp);//归并排序右部分(mid+1,right)
merge(nums,left,mid,right,temp);//合并
}
}
private void merge(int[] nums, int left, int mid, int right, int[] temp) {
int i = left; // 左部分首元素
int j = mid + 1; // 右部分首元素
int t = 0;
while(i <=mid && j <=right){//在范围之内
if(nums[i] <= nums[j]){
temp[t++] = nums[i++];
}else{
count += (mid - i + 1);//只需要这行代码
temp[t++] = nums[j++];
}
}
while (i <= mid){//右边遍历完事了 左边还剩呢
temp[t++] = nums[i++];
}
while(j <= right){//左边遍历完事了 右边还剩了
temp[t++] = nums[j++];
}
t = 0;//将temp中的元素 全部都copy到原数组里边去
while (left <=right){
nums[left++] = temp[t++];
}
}
}
执行结果:

226

被折叠的 条评论
为什么被折叠?



