在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
主要是以归并排序的思想
public class Solution {
public int InversePairs(int [] array) {
if (array==null) return 0;
if (array.length<2) return 0;
int[] copy = new int[array.length];
return merge(array,0,array.length-1,copy);
}
public int mergeArray(int[] a,int l,int m,int h,int[] tmp)
{
int count = 0;
int i = l;
int j = m+1;
int k = l;
while(i<=m&&j<=h)
{
if(a[i]>a[j])
{
tmp[k++] = a[j++];
count += m-i+1;
}
else
tmp[k++] = a[i++];
}
while(i<=m)
{
tmp[k++] = a[i++];
}
while(j<=h)
{
tmp[k++] = a[j++];
}
for (int p = l; p <= h; p++) {
a[p] = tmp[p];
}
return count;
}
public int merge(int[] a,int l,int h,int[] temp)
{
int count = 0;
if(l<h)
{
int mid = (l+h)/2;
count+=merge(a,l,mid,temp);
count+=merge(a,mid+1,h,temp);
count+=mergeArray(a,l,mid,h,temp);
}
return count;
}
}
本文介绍了一种利用归并排序思想计算数组中逆序对总数的方法。逆序对是指数组中前面的数字大于后面的数字的情况。通过递归地将数组拆分为更小的部分,并在合并过程中计算逆序对数量,最终得到整个数组的逆序对总数。
5377

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



