Skip to content

Commit 3760fca

Browse files
committed
refactor: eliminate unnecessary variables in kth largest element in an array
1 parent 354505d commit 3760fca

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

alternative/medium/kth_largest_element_in_an_array.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,20 @@
22
import heapq
33

44
def findKthLargest(nums: List[int], k: int) -> int:
5-
priority_queue = []
5+
max_heap = []
66

77
for n in nums:
8-
heapq.heappush(priority_queue, -n)
8+
heapq.heappush(max_heap, -n)
99

10-
res = 0
11-
while k > 0:
12-
res = -heapq.heappop(priority_queue)
10+
while k > 1:
11+
heapq.heappop(max_heap)
1312
k -= 1
14-
return res
13+
14+
return -heapq.heappop(max_heap)
15+
16+
# Algorithm - Max Heap
17+
# Time Complexity - O(nlogn)
18+
# Space Complexity - O(n)
1519

1620
assert findKthLargest([3,2,1,5,6,4], 2) == 5
1721
assert findKthLargest([3,2,3,1,2,4,5,5,6], 4) == 4

0 commit comments

Comments
 (0)