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)