剑指 Offer 51. 数组中的逆序对

题目

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

题目链接:剑指 Offer 51. 数组中的逆序对

示例 1:

输入: [7,5,6,4]
输出: 5

思路

使用归并排序,重点在于合的过程中,使用两个指针指向数组的末尾,使用一个指针指向临时数组的末尾。如果第一个子数组中的数字大于第二个子数组的数字,那么则构成逆序对,并且逆序对的数目等于等于第二个数组中剩余数字的个数。

代码实现

//时间复杂度0(nlogn),空间复杂度o(n)
    public int reversePairs(int[] nums) {
        if (nums.length <= 0 || nums == null) {
            return 0;
        }
        int count = getCount(nums, 0, nums.length - 1);
        return count;
    }

    public static int getCount(int[] nums, int start, int end) {
        if (start >= end) {
            return 0;
        }
        int mid = start + (end - start) / 2;
        //分解
        int left = getCount(nums, start, mid);
        int right = getCount(nums, mid + 1, end);

        //合并
        int count = 0;
        int i = mid;//左边区域的指针
        int j = end;//右边区域的指针
        int[] temp = new int[end-start + 1];
        int k = end-start;//临时数组的指针
        while (i>=start&&j>=mid+1){
            if(nums[i]>nums[j]){
                count+=(j-mid);
                temp[k--]=nums[i--];
            }else{
                temp[k--]=nums[j--];
            }
        }

        //如果左边区域有剩余部分
        while (i>=start){
            temp[k--]=nums[i--];
        }
        //如果右边区域有剩余部分
        while (j>=mid+1){
            temp[k--]=nums[j--];
        }

        //将临时数组中元素的拷贝到原来的数组中,注意并不是从头开始拷贝
        for (int l = 0; l <temp.length ; l++) {
            nums[l+start]=temp[l];
        }
        return count+left+right;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值