Leetcode 面试题51.数组中的逆序对

Leetcode 面试题51.数组中的逆序对

1 题目描述(Leetcode题目链接

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

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

限制:0 <= 数组长度 <= 50000

2 题解

  分治,归并排序,每次将数组分成两部分,分到不能再分的时候计算逆序对数,然后返回排序好的数组,比较容易看懂。

class Solution:
    def reversePairs(self, nums: List[int]) -> int:

        def DivideAndConquer(nums):
            if len(nums) <= 1:
                return nums, 0
            mid = len(nums)//2
            l, l_num = DivideAndConquer(nums[:mid])
            r, r_num = DivideAndConquer(nums[mid:])
            i, j = len(l)-1, len(r)-1
            num = 0
            while i >= 0 and j >= 0:
                if l[i] > r[j]:
                    num += j + 1
                    i -= 1
                else:
                    j -= 1
            return sorted(l+r), l_num + r_num + num

        _, res = DivideAndConquer(nums)
        return res

使用二分查找来做,题解

class Solution:
    def reversePairs(self, nums: List[int]) -> int:
        q = []
        res = 0
        for v in nums:
            i = bisect.bisect_left(q,-v)
            res += i
            q[i:i] = [-v]
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值