1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
''' This solution exceeds the time limit
class Solution:
def reversePairs(self, nums: List[int]) -> int:
def dfs(head, id):
if id == len(nums):
return 0
cnt = 0
for i in range(id, len(nums)):
if head > nums[i]:
cnt += 1
return cnt + dfs(nums[id], id+1)
return dfs(nums[0], 1) if len(nums) > 1 else 0
'''
class Solution:
def reversePairs(self, nums: List[int]) -> int:
def mergeSort(nums, low, high):
if low >= high: return 0 # Don't need to check if only one element in the partition
mid = 0, low + (high - low) // 2
ans = mergeSort(nums, low, mid) + mergeSort(nums, mid + 1, high)
l, r = low, mid + 1
tmp = []
while l <= mid and r <= high:
if nums[l] <= nums[r]:
tmp.append(nums[l])
l += 1
else:
tmp.append(nums[r])
ans += mid - l + 1 # nums[l] ... nums[mid] > num[r]
r += 1
while l <= mid: # Append the rest elements if needed
tmp.append(nums[l])
l += 1
while r <= high:
tmp.append(nums[r]) # Append the rest elements if needed
r += 1
nums[low: high+1] = tmp
return ans
return mergeSort(nums, 0, len(nums)-1)
|