Files
leetcode/apps/docs/content/heap-priority-queue/215-kth-largest-element-in-an-array.mdx
T

59 lines
1.3 KiB
Plaintext
Raw Normal View History

---
title: '215. Kth Largest Element in an Array'
description: Given an integer array nums and an integer k, return the k^th largest element in the array
sidebar:
label: 'Kth Largest Element in an Array'
badge: 'Medium'
---
<Badge variant="accent">Array</Badge>
### Example 1:
- Input: `nums = [3,2,1,5,6,4], k = 2`
- Output: `5`
### Example 2:
- Input: `nums = [3,2,3,1,2,4,5,5,6], k = 4`
- Output: `4`
### Constraints:
- `1 <= k <= nums.length <= 10^5`
- `-10^4 <= nums[i] <= 10^4`
## Approach
```mermaid
flowchart TD
S(["findKthLargest(nums, k)"]) --> F{"more i in range(len(nums))?"}
F -- yes --> N["nums[i] = -nums[i] — negate so the min-heap acts as a max-heap"]
N --> F
F -- no --> H["heapq.heapify(nums)"]
H --> W{"more _ in range(k - 1)?"}
W -- yes --> P["heapq.heappop(nums) — discard the k-1 largest"]
P --> W
W -- no --> E(["return -heapq.heappop(nums)"])
```
## Solution
```py
import heapq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
for i in range(len(nums)):
nums[i] = -nums[i]
heapq.heapify(nums)
for _ in range(k - 1):
heapq.heappop(nums)
return -heapq.heappop(nums)
```
## Explanation
<YouTube id="XEmy13g1Qxc" title="Kth Largest Element in an Array - Quick Select - Leetcode 215 - Python" />