Skip to content

Commit 9631d79

Browse files
authored
Create Kth Largest Element in an Array - Leetcode 215.py
1 parent 3a4f89d commit 9631d79

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import heapq
2+
class Solution:
3+
def findKthLargest(self, nums: List[int], k: int) -> int:
4+
for i in range(len(nums)):
5+
nums[i] = -nums[i] # Max Heap
6+
7+
heapq.heapify(nums)
8+
9+
for _ in range(k-1):
10+
heapq.heappop(nums)
11+
12+
return -heapq.heappop(nums)
13+
# Max Heap of size n
14+
# Time: O(n + k log n)
15+
# Space: O(1)
16+
17+
import heapq
18+
class Solution:
19+
def findKthLargest(self, nums: List[int], k: int) -> int:
20+
min_heap = []
21+
22+
for num in nums:
23+
if len(min_heap) < k:
24+
heapq.heappush(min_heap, num)
25+
else:
26+
heapq.heappushpop(min_heap, num)
27+
28+
return min_heap[0]
29+
# Min heap of size k
30+
# Time: O(n log k)
31+
# Space: O(k)
32+

0 commit comments

Comments
 (0)