-
Notifications
You must be signed in to change notification settings - Fork 24
/
215 - Kth Largest Element.py
67 lines (62 loc) · 2.09 KB
/
215 - Kth Largest Element.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Solution 1: Use a heap, pretty straight forward
# Runtime: O(n + klogn) since it takes O(n) time to build the heap and O(klogn) to pop k times
import heapq
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
heapq.heapify(nums)
for i in range(len(nums)-k):
heapq.heappop(nums)
return nums[0]
# Solution 2: Use quick select algorithm, this is pretty tricky!
# I recommend studying up on a partitioning scheme first. A few
# common ones are:
# - Lomuto
# - Hoare's
# - Dutch National Flag -> I'm using this one since we already used it in #75 - Sort Colors
# Runtime: Average case O(n), worst case O(n^2) but this is unlikely since we're choosing
# a random pivot each time
import random
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
random.seed()
return self.quickSelect(nums, 0, len(nums)-1, len(nums)-k)
def quickSelect(self, nums, left, right, k):
pivotIndex = random.randint(left, right)
pivotIndex = self.partition(nums, left, right, pivotIndex)
if pivotIndex == k:
return nums[pivotIndex]
elif pivotIndex < k:
return self.quickSelect(nums, pivotIndex+1, right, k)
else:
return self.quickSelect(nums, left, pivotIndex-1, k)
# Let's use DNF (dutch national flag) algorithm for the partition
def partition(self, nums, left, right, pivotIndex):
pivot = nums[pivotIndex]
i = left
j = left
k = right
while j <= k:
if nums[j] < pivot:
self.swap(nums, i, j)
i += 1
j += 1
elif nums[j] > pivot:
self.swap(nums, j, k)
k -= 1
else:
j += 1
return k # k is the final location of the pivot
def swap(self, nums, i, j):
tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp