1
1
from typing import List
2
2
import heapq
3
3
4
+ # Algorithm - Max Heap
5
+ # Time Complexity - O(nlogn)
6
+ # Space Complexity - O(n)
4
7
def findKthLargest (nums : List [int ], k : int ) -> int :
5
8
max_heap = []
6
9
@@ -13,9 +16,36 @@ def findKthLargest(nums: List[int], k: int) -> int:
13
16
14
17
return - heapq .heappop (max_heap )
15
18
16
- # Algorithm - Max Heap
17
- # Time Complexity - O(nlogn)
18
- # Space Complexity - O(n)
19
+ # Algorithm - Quick Select
20
+ # Time Complexity - O(n)
21
+ # Space Complexity - O(1)
22
+ def findKthLargestV2 (nums : List [int ], k : int ) -> int :
23
+ k = len (nums ) - k
24
+ left , right = 0 , len (nums ) - 1
19
25
26
+ while left < right :
27
+ pivot = partition (nums , left , right )
28
+ if pivot < k :
29
+ left = pivot + 1
30
+ elif pivot > k :
31
+ right = pivot - 1
32
+ else :
33
+ break
34
+
35
+ return nums [k ]
36
+
37
+ def partition (nums : List [int ], left : int , right : int ) -> int :
38
+ pivot = left
39
+ for i in range (left , right ):
40
+ if nums [i ] <= nums [right ]:
41
+ nums [i ], nums [pivot ] = nums [pivot ], nums [i ]
42
+ pivot += 1
43
+
44
+ nums [pivot ], nums [right ] = nums [right ], nums [pivot ]
45
+
46
+ return pivot
47
+
20
48
assert findKthLargest ([3 ,2 ,1 ,5 ,6 ,4 ], 2 ) == 5
21
- assert findKthLargest ([3 ,2 ,3 ,1 ,2 ,4 ,5 ,5 ,6 ], 4 ) == 4
49
+ assert findKthLargestV2 ([3 ,2 ,1 ,5 ,6 ,4 ], 2 ) == 5
50
+ assert findKthLargest ([3 ,2 ,3 ,1 ,2 ,4 ,5 ,5 ,6 ], 4 ) == 4
51
+ assert findKthLargestV2 ([3 ,2 ,3 ,1 ,2 ,4 ,5 ,5 ,6 ], 4 ) == 4
0 commit comments