数组中的逆序对 - 剑指Offer第51题

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

示例 :

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

解题思路:

参考LeetCode解题思路:
https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/solution/shu-zu-zhong-de-ni-xu-dui-by-leetcode-solution/

package com.alibaba.study.offer;

/**
 * @Auther: wjj
 * @Date: 2020/12/14 21:14
 * @Description:
 */
public class Offer51 {

    public static void main(String[] args) {
        System.out.printf("结果:" + reversePairs(new int[] {7,5,6,4}));
    }

    public static int reversePairs(int[] nums) {
        int len = nums.length;
        if(len < 2){
            return 0;
        }
        int[] temp = new int[len];
        return merge(nums, 0, len-1, temp);
    }

    private static int merge(int[] nums, int left, int right, int[] temp){
        if(left == right){
            return 0;
        }
        // 当left和right非常大时,可能会溢出
        int mid = left + (right - left)/ 2;

        int leftCount = merge(nums, left, mid, temp);
        int rightCount = merge(nums, mid + 1, right, temp);
        // 如果左数组最大值比右数组最小值小,那么无逆序对
        if(nums[mid] <= nums[mid + 1]){
            return leftCount + rightCount;
        }
        // 计算两个有序数组的逆序对
        int crossCount = caculateCorssCount(nums, left, mid, right, temp);

        return leftCount + crossCount + rightCount;
    }

    private static int caculateCorssCount(int[] nums, int left, int mid, int right, int[] temp) {
        for(int i=left; i<=right; i++){
            temp[i] = nums[i];
        }
        int i = left;
        int j = mid + 1;
        int count = 0;

        for(int k = left; k<= right; k++){

            if(i == mid + 1){
                nums[k] = temp[j];
                j++;
            } else if(j == right + 1){
                nums[k] = temp[i];
                i++;
            } else if(temp[i] <= temp[j]){
                nums[k] = temp[i];
                i++;
            } else {
                // 只有右数组元素入数组时,才需要计算逆序对,理解一下,
                // 右数组元素入原数组,表示这个元素值比左数组剩余的值都要小,
                // 构成逆序对。
                nums[k] = temp[j];
                j++;
                count += (mid-i+1);
            }
        }
        return count;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值