-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0215-kth-largest-element-in-an-array.py
44 lines (40 loc) · 1.28 KB
/
0215-kth-largest-element-in-an-array.py
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
# Solution: Sorting
# Time Complexity:
# - Best Case: O(n*log(k))
# - Average Case: O(n*log(k))
# - Worst Case:O(n*log(k))
# Extra Space Complexity: O(k)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heapify(nums)
while len(nums) > k:
heappop(nums)
return nums[0]
# Solution: Sorting
# Time Complexity:
# - Best Case: O(n)
# - Average Case: O(n*log(n))
# - Worst Case:O(n*log(n))
# Extra Space Complexity: O(n)
class Solution1:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
return nums[len(nums) - k]
# Solution: QuickSelect
# Time Complexity: O(n)
# Extra Space Complexity: O(n)
class Solution2:
def findKthLargest(self, nums: List[int], k: int) -> int:
pivot = random.choice(nums)
left = [num for num in nums if num > pivot]
mid = [num for num in nums if num == pivot]
right = [num for num in nums if num < pivot]
length_left = len(left)
length_right = len(right)
length_mid = len(mid)
if k <= length_left:
return self.findKthLargest(left, k)
elif k > length_left + length_mid:
return self.findKthLargest(right, k - length_mid - length_left)
else:
return mid[0]