File tree 1 file changed +50
-0
lines changed 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/reverse-pairs/
2
+
3
+ class Solution :
4
+ def __init__ (self ):
5
+ self .count = 0
6
+
7
+ def reversePairs (self , nums : List [int ]) -> int :
8
+ self .mergeSort (nums )
9
+ return self .count
10
+
11
+ def mergeSort (self , nums ):
12
+ if len (nums ) > 1 :
13
+ # calculate mid
14
+ mid = len (nums ) // 2
15
+ # divide the input array in to right and left
16
+ left = nums [:mid ]
17
+ right = nums [mid :]
18
+
19
+ self .mergeSort (left )
20
+ self .mergeSort (right )
21
+
22
+ # the tricky part - updating the count of number of possible pairs
23
+ j = 0
24
+ for i in range (len (left )):
25
+ while j < len (right ) and left [i ] > 2 * right [j ]:
26
+ j += 1
27
+ self .count += j
28
+
29
+ # merge two sorted array
30
+ i = j = k = 0
31
+ while i < len (left ) and j < len (right ):
32
+ if left [i ] <= right [j ]:
33
+ nums [k ] = left [i ]
34
+ k += 1
35
+ i += 1
36
+ else :
37
+ nums [k ] = right [j ]
38
+ k += 1
39
+ j += 1
40
+ while i < len (left ):
41
+ nums [k ] = left [i ]
42
+ k += 1
43
+ i += 1
44
+ while j < len (right ):
45
+ nums [k ] = right [j ]
46
+ k += 1
47
+ j += 1
48
+
49
+ # Time: O(n log(n))
50
+ # Space: O(n)
You can’t perform that action at this time.
0 commit comments