Skip to content

Commit e24c650

Browse files
committed
Sync LeetCode submission Runtime - 105 ms (15.79%), Memory - 28.9 MB (13.40%)
1 parent 1302a66 commit e24c650

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p>
2+
3+
<p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p>
4+
5+
<p>Can you solve it without sorting?</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
<pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2
10+
<strong>Output:</strong> 5
11+
</pre><p><strong class="example">Example 2:</strong></p>
12+
<pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4
13+
<strong>Output:</strong> 4
14+
</pre>
15+
<p>&nbsp;</p>
16+
<p><strong>Constraints:</strong></p>
17+
18+
<ul>
19+
<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
20+
<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
21+
</ul>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Approach 2: Min-Heap
2+
3+
# Time: O(n * log k)
4+
# Space: O(k)
5+
6+
import heapq
7+
8+
class Solution:
9+
def findKthLargest(self, nums: List[int], k: int) -> int:
10+
heap = []
11+
heapq.heapify(heap)
12+
13+
for num in nums:
14+
heapq.heappush(heap, num)
15+
if len(heap) > k:
16+
heapq.heappop(heap)
17+
18+
return heap[0]
19+

0 commit comments

Comments
 (0)