Files
leetcode/apps/docs/content/(03-hierarchical)/heap-priority-queue/215_kth-largest-element-in-an-array.mdx
T

63 lines
1.5 KiB
Plaintext

---
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
icon: dot
topics:
- { name: "Array", slug: "array" }
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
- { name: "Sorting", slug: "sorting" }
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
- { name: "Quickselect", slug: "quickselect" }
video: "XEmy13g1Qxc"
issue: "https://github.com/prdlk/leetcode/issues/118"
sidebar:
label: 'Kth Largest Element in an Array'
badge: 'Medium'
---
### 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)
```