Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 915d4cf

Browse files
authored
Create Kth_largest_element_in_array.py
1 parent acbf861 commit 915d4cf

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Solution - 1: Using List & Sort | Time: O(NlogN)
2+
class Solution:
3+
def findKthLargest(self, nums: List[int], k: int) -> int:
4+
nums.sort(reverse=True)
5+
return nums[k-1]
6+
7+
8+
# Solution - 2: Using Heap | Time: O(N) to build heap + O(KlogN) to find the Kth largest item
9+
import heapq
10+
class Solution:
11+
def findKthLargest(self, nums: List[int], k: int) -> int:
12+
# To put into Max Heap
13+
nums = [-x for x in nums]
14+
heapq.heapify(nums)
15+
while k:
16+
ans = heapq.heappop(nums)
17+
k -= 1
18+
19+
return -ans
20+
21+
22+
23+
24+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /