题目如下:

【leetcode】493. Reverse Pairs

解题思路:本题要求的是数组每个元素和所有排在这个元素后面的元素的值的二倍做比较。我们可以先把数组所有元素的二倍都算出来,存入一个新的数组newlist,并按升序排好。而后遍历nums数组的每个元素i,通过二分查找的方法在newlist中找到值比i小的元素中下标最大的那个(记为inx),那么符合条件i元素的reverse paris就是inx,累计所有的inx即可得到结果。

代码如下:

class Solution(object):
    def reversePairs(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = 0
        nl = []
        for i in nums:
            nl.append(2*i)
        nl.sort()
        res = 0
        import bisect
        for i in nums:
            inx = bisect.bisect_left(nl,2*i)
            del nl[inx]
            inx = bisect.bisect_left(nl, i)
            res += inx

        return res
        

 

相关文章:

  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-01-13
  • 2022-12-23
  • 2022-12-23
  • 2021-07-14
  • 2021-08-08
猜你喜欢
  • 2021-04-02
  • 2022-12-23
  • 2022-01-22
  • 2022-01-06
  • 2022-12-23
  • 2021-10-06
相关资源
相似解决方案