剑指offer: 数组中的逆序对

题目描述:

        在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

思路:

        归并排序的思想(先递归,再排序)。array为原来的数组,copy为array复制后的数组,将copy的数组排好序最后依次赋给array。mid每次指向的是low与high的中间位置。定义三个变量,i,j,k,   i最初指向mid的位置(也就是归并中左边最大的数的位置),j和k指向high的位置,k用来每次存放较大值时对copy数组的遍历,循环的临界条件是(i>=low && j>mid), 

    如果i所在的位置大于j所在的位置,就说明i所在的位置的值大于所有 mid+1到 j 位置的数,每次都将这个较大的值放到copy[j--]位置中,这时候逆序对的个数是count += j-mid; ,最后将没有遍历完的数依次放入copy数组中。将整个copy数组复制到array中,继续递归。

注意:

需要考虑count数值过大的情况


代码实现:

public int InversePairs(int [] array) {
		if(array == null || array.length == 0){
			return 0;
		}
		int[] copy = new int[array.length];
		for(int i=0; i<array.length; i++){
			copy[i] = array[i];
		}
		int count = InversePairsCore(array,copy,0,array.length-1);
		return count;
	}
    private int InversePairsCore(int[] array, int[] copy, int low, int high) {
    	if(low==high){
    		return 0;
    	}
    	int mid = (low+high)/2;
		int left = InversePairsCore(array,copy,low,mid)%1000000007;
		int right = InversePairsCore(array,copy,mid+1,high)%1000000007;
		int count = 0;
		int i=mid,j=high,k=high;
		while(i>=low && j>mid){
			if(array[i] > array[j]){
				count += j-mid;
				copy[k--] = array[i--];
				if(count>=1000000007)//数值过大求余
	                {
	                    count%=1000000007;
	                }
			}else{
				copy[k--] = array[j--];
			}
		}
		for(; i>=low; i--){
			copy[k--] = array[i];	
		}
		for(; j>mid; j--){
			copy[k--] = array[j];	
		}
//		将copy的值放入array
		for(int m=low; m<=high; m++){
			array[m] = copy[m];
		}
		return (left+right+count)%1000000007;
	}

猜你喜欢

转载自blog.csdn.net/weixin_38108266/article/details/80958954