题目描述: 有一组数,对于其中任意两个数组,若前面一个大于后面一个数字,则这两个数字组成一个逆序对,计算给定数组中的逆序对个数。
给定一个int数组A和它的大小n,请返回A中的逆序对个数。
测试样例:
[1,2,3,4,5,6,7,0],8
返回:7
解题思路:
**思路1:**顺序扫描整个数组,没扫描到一个数,就比较该数与后面数的大小,如果该数小于大于后面的数,就构成逆序对。若该数组中有n个数,则此算法的时间复杂度为O(n^2)。
public class Demo1 {
public static int Count(int[] A,int n){
int count = 0;
for(int i = 0;i<A.length;i++){
for(int j = i+1;j<A.length;j++){
if (A[i] > A[j])
count++;
}
}
return count;
}
public static void main(String[] args) {
int[] A = new int[]{1,2,3,4,5,6,7,0};
int c = Count(A,A.length);
System.out.println(c);
}
}
思路2: 利用分治思想,采用归并排序来解决,归并排序的时间复杂度为O(n*log(n))。例如{6,5,4,7}这个数组,有4个数。
(1)先将数组分成一个一个的子数组,直到数组内只有一个数,即分成了{6}{5}{4}{7}四个数组。
(2)再将{6}{5}合并,一边排序一边统计逆序对。{4}{7}合并,一边排序一边统计逆序对。得到{5,6}{4,7}两个数组。
(3)再将{5,6}{4,7}两数组合并,一边排序一边统计逆序对,得到{4,5,6,7}结束。
public class Main2{
public static int count(int[] A,int n){
if(A == null || n == 0){
return 0;
}
return mergeSortRecursion(A,0,A.length);
}
public static int mergeSortRecursion(int[] array,int low,int high){
//[low,high)
if(high - 1 == low){
return 0;
}
int mid = (high + low)/2;
return mergeSortRecursion(array,low,mid)+ mergeSortRecursion(array,mid,high)+mergeCount(array,low,mid,high);
}
public static int mergeCount(int[] array,int low,int mid,int high){
int i = low;
int j = mid;
int length = high - low;
int[] newArray = new int[length];
int k = 0;
int sumReverse = 0;
//选择小的放入到newArray中
while(i<mid && j<high){
if(array[i] <= array[j]){
newArray[k++] = array[i++];
}
else{
sumReverse += (mid - i);
newArray[k++] = array[j++];
}
}
while(i < mid){
newArray[k++] = array[i++];
}
while(j < high){
newArray[k++] = array[j++];
}
//从newArray搬回到array中
for(int t = 0;t < length;t++){
array[low + t] = newArray[t];
}
return sumReverse;
}
public static void main(String[] args) {
int[] a = {1,6,7,8,2,5,3};
int r = count(a,7);
System.out.println(r);
}
}