数组中的逆序对-51
在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
输入一个数组,求出这个数组中的逆序对的总数。
样例
输入:[1,2,3,4,5,6,0]
输出:6
思路:
如果遍历数组,对每个数字都和后面的数字比较大小,时间复杂度为 O(n^2),效率太低。
利用归并排序的思想,先将数组分解成为 n 个长度为 1 的子数组,然后进行两两合并同时排好顺序。
在对两个子区域合并排序时,记左边区域(下标为 start ~ mid)的指针为 i,右边区域(下标为mid+1~end)的指针为 j,两个指针都指向该区域内最大的数字,排序时:
(1)如果 i 指向的数字大于 j 指向的数字,说明:逆序对有 j - mid个,我们把i指向的数字放入临时创建的排序数组中,然后令 i - 1,指向该区域前一个数字,继续进行排序;
(2)如果 i 指向的数字小于等于 j 指向的数字,说明暂时不存在逆序对,将 j 指向的数字放入临时创建的排序数组中,然后令 j - 1,指向该区域前一个数字,继续进行排序;
(3)某一子区域数字都放入排序数组后,将另一个子区域剩下的数字放入排序数组中,完成排序;
(4)最后将排序好的数字按顺序赋值给原始数组的两个子区域,以便合并后的区域与别的区域合并。
[外链图片转存失败(img-HiZ35F4l-1568129213400)(…/图片/1407330-20181114084308747-1926985388.png)]
使用全局变量:
class Solution {
private int count = 0;
public int inversePairs(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int left = 0, right = nums.length - 1;
getcount(nums, left, right);
return count;
}
public void getcount(int[] nums, int left, int right){
if(left >= right) return;
int mid = left + (right - left) / 2;
getcount(nums, left, mid);
getcount(nums, mid + 1, right);
merge(nums, left, mid, right);
}
public void merge(int[] nums, int left, int mid, int right){
int i = mid, j = right;
int[] temp = new int[right-left+1];
int k = right - left;
while(i >= left && j >= mid+1){
if(nums[i] > nums[j]){
count += (j - mid);
temp[k--] = nums[i--];
}else{
temp[k--] = nums[j--];
}
}
while(i >= left) temp[k--] = nums[i--];
while(j >= mid+1) temp[k--] = nums[j--];
for(int h = 0; h < temp.length; h++){
nums[h+left] = temp[h];
}
}
}
不使用全局变量:
public class InversePairs {
public int inversePairs(int[] array) {
if (array == null || array.length <= 0) return 0;
return getCount(array, 0, array.length - 1);
}
private int getCount(int[] array, int start, int end) {
if (start >= end) return 0;
int mid = (end + start) >> 1;
int left = getCount(array, start, mid);
int right = getCount(array, mid + 1, end);
//合并
int count = 0;
int i = mid; //左边区域的指针
int j = end; //右边区域的指针
int[] temp = new int[end - start + 1]; //临时区域
int k = end - start; //临时区域的指针
while (i >= start && j >= mid + 1) {
if (array[i] > array[j]) {
count += (j - mid);
temp[k--] = array[i--];
} else {
temp[k--] = array[j--];
}
}
while (i >= start) temp[k--] = array[i--];
while (j >= mid + 1) temp[k--] = array[j--];
for (k = 0; k < temp.length; k++)
array[k + start] = temp[k];
return count + left + right;
}
}