Skip to content

Commit 4181ff2

Browse files
committed
Create 215-kth_largest_elem_in_array.py
1 parent 0e4b50e commit 4181ff2

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

Diff for: 215-kth_largest_elem_in_array.py

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import heapq
2+
3+
"""
4+
https://leetcode.com/problems/kth-largest-element-in-an-array/
5+
6+
Strat: Use a heap. Building it with the built-in library (documentation:
7+
https://docs.python.org/2/library/heapq.html#heapq.heapify). After it's
8+
built, just remove (nums - k) numbers from it. The last number you
9+
remove will be the k-th largest number.
10+
11+
Can also use QuickSelect, with average runtime of O(n), but it's not guranteed
12+
https://en.wikipedia.org/wiki/Quickselect
13+
"""
14+
15+
class Solution(object):
16+
def findKthLargest(self, nums, k):
17+
"""
18+
:type nums: List[int]
19+
:type k: int
20+
:rtype: int
21+
"""
22+
heapq.heapify(nums) #turn nums from a list into a min heap
23+
24+
for _ in range(len(nums) + 1 - k):
25+
elem = heapq.heappop(nums)
26+
27+
return elem
28+
29+
def findKthLargest(self, nums, k):
30+
"""
31+
:type nums: List[int]
32+
:type k: int
33+
:rtype: int
34+
"""
35+
heapq.heapify(nums)
36+
37+
k_largest = heapq.nlargest(k, nums) #grab the list of k largest nums
38+
return k_largest[-1] #last elem of nlargest
39+
40+
41+
"""
42+
A nice quick select I found
43+
"""
44+
# from random import randint
45+
46+
# class Solution(object):
47+
# def findKthLargest(self, nums, k):
48+
# """
49+
# :type nums: List[int]
50+
# :type k: int
51+
# :rtype: int
52+
# """
53+
# def partition(p, r):
54+
# x = nums[r]
55+
# i = p-1
56+
# for j in range(p,r):
57+
# if nums[j] < x:
58+
# i += 1
59+
# nums[i], nums[j] = nums[j], nums[i]
60+
# nums[i+1],nums[r] = nums[r], nums[i+1]
61+
# return i+1
62+
63+
# def random_partition(p,r):
64+
# ri = randint(p,r)
65+
# nums[ri], nums[r] = nums[r], nums[ri]
66+
# return partition(p, r)
67+
68+
# def select(p, r, k):
69+
# if p == r:
70+
# return nums[p]
71+
# q = random_partition(p, r)
72+
# i = q-p+1
73+
# if i == k:
74+
# return nums[q]
75+
# elif k < i:
76+
# return select(p, q-1, k)
77+
# else:
78+
# return select(q+1, r, k-i)
79+
80+
# return select(0, len(nums)-1, len(nums)-k+1)
81+
82+
83+
84+
sol = Solution().findKthLargest([1,4,6,3,2], 2)
85+
print(sol)

0 commit comments

Comments
 (0)