topic
For two numbers in the array, if the first number is greater than the following number, the two numbers form a reverse pair. Enter an array and find the total number of reverse pairs in this array.
Example 1:
Input: [7,5,6,4]
Output: 5
Ideas
The brute force method is to traverse the array with two for loops and compare each pair of numbers in the array, but it will time out.
How to reduce the number of comparisons?
Use the idea of merging and sorting.
The original array: [7,5,6,4]
is divided into two: left = [7,5], right = [6,4]
Sort each sub-array: left = [5,7], right = [4 ,6] In
the process of merging, find the reverse pair:
The first element 5 in left is greater than the first element 4 in right, which can form a reverse pair. Since the two sub-arrays are both sorted, the elements after 5 are all greater than 4, which can be determined without comparison, and both can form a reverse pair with 4.
On the basis of merge sorting, add the number of statistical reverse order pairs.
Code
class Solution:
def reversePairs(self, nums: List[int]) -> int:
self.count = 0
def Merge(left, right, s):
i, j, k = 0, 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
s[k] = left[i]
i += 1
k += 1
else:
self.count += len(left)-i
s[k] = right[j]
j += 1
k += 1
while i < len(left):
s[k] = left[i]
i += 1
k += 1
while j < len(right):
s[k] = right[j]
j += 1
k += 1
def MergeSort(nums):
if len(nums) < 2:
return nums
mid = len(nums)//2
left = nums[:mid]
right = nums[mid:]
MergeSort(left)
MergeSort(right)
Merge(left, right, nums)
MergeSort(nums)
return self.count
the complexity
Time complexity: O(nlogn)
Space complexity: O(n)