剑指offer——数组中的逆序对

题目描述:

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

输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5


思路:

要找到数组中的逆序对,一种思路是每遍历到一个元素的时候就和后面的元素进行一一比较,这种算法的时间复杂度是O(n2),所以不是很理想。我们可以借鉴归并排序的思想,把数组划分为子数组,然后对每个子数组中的逆序对数进行统计,统计完成后再并到一个新的数组中进行统计,这样就化整为零,实现了高效统计。总计起来思路就是:首先把数组划分为子数组,然后统计子数组中的逆序对数,然后继续统计相邻子数组的逆序对数,在统计相邻子数组中的逆序对数的时候,需要使用两个指针,一个指向第一个数组的头部,一个指向第二个数组的头部,如果第一个指针指向的元素大于后面的,说明相邻之间存在逆序对,并把较大的那个数拷贝到一个临时数组中,然后指针往前移动,直到所有的子数组以及相邻的子数组的逆序对数统计完毕。


代码实现:

public class Solution {
    int resultCount = 0; // 逆序对的数量      
    public int InversePairs(int[] array) {
        int len = array.length;
        int first = 0;
        int last = len - 1;
        int temp[] = new int [len];// 辅助数组,用以保存合并后的数组
        mergeSort(array, first, last, temp);
        return resultCount%1000000007 ;
    }

    private void mergeSort(int[] array, int first, int last, int[] temp) {
        if(first < last){
            int mid = (first + last) / 2;
            mergeSort(array, first, mid, temp);// 左子数组有序
            mergeSort(array, mid+1, last, temp);// 右子数组有序
            mergeArray(array, first, mid, last, temp); // 合并数组
        }
    }

    // 合并两个有序数组
    private void mergeArray(int[] array, int first, int mid, int last, int[] temp) {
        int lFirst = first, lLast = mid; // 左子数组的首尾标识;
        int rFirst = mid + 1, rLast = last; // 右子数组的首尾标识;
        int i = 0;

        while (lFirst <= lLast && rFirst <= rLast) {
            // 两个子数组都不为空,比较数组头
            if (array[lFirst] <= array[rFirst]) { // 左子数组头小于右子数组,表头不存在逆序
                temp[i] = array[lFirst];
                i++;
                lFirst++;
            } else {
            // 左子数组头大于右子数组头,说明左子数组中所有元素都大于右子数组头,所以一共有左子数组
            // 个数的逆序对,resultCount += lLast - lFirst + 1
                resultCount = resultCount + lLast - lFirst + 1;
                if(resultCount>1000000007)//数值过大求余
                {
                    resultCount%=1000000007;
                }
                temp[i] = array[rFirst];
                i++;
                rFirst++;
            }
        }          
        // 右子数组空
        while (lFirst <= lLast) {
            temp[i++] = array[lFirst++];
        }          
        // 左子数组空
        while (rFirst <= rLast) {
            temp[i++] = array[rFirst++];
        }         
        // 将辅助数组中的元素交给原数组
        for (int num = 0; num < i; num++) {  //主要用于排序的
            array[first + num] = temp[num];
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值