剑指 Offer 51. 数组中的逆序对(困难)

该篇博客详细介绍了如何利用归并排序和离散化树状数组两种方法解决《剑指Offer》中数组中的逆序对问题。作者提供了完整的Java代码实现,并附带了官方题解链接,帮助读者理解这两种高效算法的思路和应用。

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

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

题目链接

https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/

代码连接:

https://gitee.com/aninstein/HappyJava/blob/master/learn_java/src/leetcode/offer100/arrays/HardReversePairs.java

题目解析:

  • 方法1:归并排序
  • 方法2:离散化树状数组

官方题解: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 leetcode.offer100.arrays;


import base.Utils;

/**
 * 题目:剑指 Offer 51. 数组中的逆序对
 * 题目连接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/
 *
 * 方法1:归并排序
 * 方法2:离散化树状数组
 * 官方题解:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/solution/shu-zu-zhong-de-ni-xu-dui-by-leetcode-solution/
 *
 */
public class HardReversePairs {

    /**
     * 1. 使用归并排序解题
     * @param nums
     * @return
     */
    public static int reversePairs(int[] nums) {
        int len = nums.length;

        if (len < 2) {
            return 0;
        }
        int[] temp = new int[len];
        return countReversePairs(nums, temp, 0, len - 1);
    }

    private static int countReversePairs(int[] nums, int[] temp, int left, int right) {
        if (left == right) {
            return 0;
        }

        int mid = Utils.midNumber(left, right);
        int leftPairs = countReversePairs(nums, temp, left, mid);
        int rightPairs = countReversePairs(nums, temp, mid + 1, right);

        if (nums[mid] <= nums[mid + 1]) {
            return leftPairs + rightPairs;
        }

        int crossPairs = countAndMerge(nums, temp, left, mid, right);
        return leftPairs + crossPairs + rightPairs;
    }

    private static int countAndMerge(int[] nums, int[] temp, int left, int mid, int right) {
        for (int i = left; i <= right ; i++) {
            temp[i] = nums[i];
        }

        int i = left, j = mid + 1;
        int count = 0;
        for (int k = left; k <= right; k++) {
            if (i == mid + 1) {
                nums[k] = temp[j++];
            } else if (j == right + 1) {
                nums[k] = temp[i++];
            } else if (temp[i] <= temp[j]) {
                nums[k] = temp[i++];
            } else {
                nums[k] = temp[j++];
                count += (mid - i + 1);
            }
        }
        return count;
    }

    public static void main(String[] args) {

    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值