牛客(35)数组中的逆序对

本文介绍了一种高效的逆序对计数算法,利用归并排序思想,在保证数组元素唯一性的前提下,计算数组中逆序对的总数,并对结果进行取模运算。该算法针对不同规模的数据进行了优化,确保在大数据量下仍能高效运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

//    public static int InversePairs(int[] array) {
////        超时
//        int count = 0;
//        for (int i=0; i<array.length;i++){
//            for (int j=i+1;j<array.length;j++){
//                if (array[i]>=array[j]){
//                    count++;
//                }
//            }
//        }
//        return count%1000000007;
//    }

    public static int InversePairs(int[] arr) {
        int[] temp = new int[arr.length];//在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间
        return sort(arr, 0, arr.length - 1, temp);
    }

    private static int sort(int[] arr, int left, int right, int[] temp) {
        if (left >= right) {
            return 0;
        }
        int count = 0;
        int mid = (left + right) / 2;
        int leftCount = sort(arr, left, mid, temp);//左边归并排序,使得左子序列有序
        int rightCount = sort(arr, mid + 1, right, temp);//右边归并排序,使得右子序列有序


        int i= mid;
        int j=right;
        while (i>=left&&j>mid){
            if (arr[i]>arr[j]){
                count += j-mid;
                //不加判断通过50%
                if(count>=1000000007)//数值过大求余
                {
                    count%=1000000007;
                }
                i--;
            }else{
                j--;
            }
        }
        merge(arr, left, mid, right, temp);//将两个有序子数组合并操作
        //75%通过
//        return count + leftCount + rightCount;
        return (count + leftCount + rightCount)%1000000007;
    }

    private static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;//左序列指针
        int j = mid + 1;//右序列指针
        int t = 0;//临时数组指针
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t++] = arr[i++];
            } else {
                temp[t++] = arr[j++];
            }
        }
        while (i <= mid) {//将左边剩余元素填充进temp中
            temp[t++] = arr[i++];
        }
        while (j <= right) {//将右序列剩余元素填充进temp中
            temp[t++] = arr[j++];
        }
        t = 0;
        //将temp中的元素全部拷贝到原数组中
        while (left <= right) {
            arr[left++] = temp[t++];
        }
    }

 

转载于:https://www.cnblogs.com/kaibing/p/9046474.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值