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.
I am just using the merge sort to do this and while doing merging process, I am piggyback checking the condition nums[i] > 2*nums[j]
. However, it is timing out for last test case. Help? Link.
class Solution(object):
def reversePairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def merge(left, right):
#print(left, right)
if not left or not right:
return (0, left + right)
#if everything in left is less than right
left_idx, right_idx, count = 0, 0, 0
merged_output = []
while left_idx < len(left) and right_idx < len(right):
#print(left[left_idx], right[right_idx])
if left[left_idx] > 2*right[right_idx]:
count += len(left) - left_idx
right_idx += 1
else:
left_idx += 1
left_idx, right_idx = 0, 0
while left_idx < len(left) and right_idx < len(right):
if left[left_idx] > right[right_idx]:
merged_output += [right[right_idx]]
right_idx += 1
else:
merged_output += [left[left_idx]]
left_idx += 1
if left_idx == len(left):
merged_output += right[right_idx:]
else:
merged_output += left[left_idx:]
return (count, merged_output)
def partition(nums):
count = 0
if len(nums) == 1 or not nums:
return (0, nums)
pivot = len(nums)//2
left_count, l = partition(nums[:pivot])
right_count, r = partition(nums[pivot:])
temp_count, temp_list = merge(l, r)
#print(temp_count)
return (count + left_count + right_count + temp_count, temp_list)
return partition(nums)[0]