Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].
You need to return the number of important reverse pairs in the given array.
Example1:
Input: [1,3,2,3,1] Output: 2
Example2:
Input: [2,4,3,5,1] Output: 3
Note:
- The length of the given array will not exceed
50,000. - All the numbers in the input array are in the range of 32-bit integer.
----------------------------------------------------------------------------------------------------------
The key for this problem is to seperate counting and sorting into 2 diff stages:
class Solution:
def reversePairs(self, nums):
l = len(nums)
def dfs(nums, lo, hi):
if (lo >= hi):
return 0
mid = lo + ((hi - lo) >> 1)
p1 = dfs(nums, lo, mid)
p2 = dfs(nums, mid+1, hi)
p3 = 0
i, j = mid, hi
while (i >= lo and j >= mid+1):
if (nums[i] > nums[j]*2):
p3 += (j-mid)
i -= 1
else:
j -= 1
nums[lo:hi + 1] = sorted(nums[lo:hi + 1])
return p1 + p2 + p3
return dfs(nums, 0, l - 1)
重要逆序对计数

本文介绍了一种算法,用于解决在一个整数数组中找出所有重要逆序对的问题。重要逆序对定义为:如果i<j且nums[i]>2*nums[j],则(i,j)构成一个重要逆序对。文章通过递归分解和排序策略,实现了一个高效解决方案。
2141

被折叠的 条评论
为什么被折叠?



