---
# System prepended metadata

title: Leetcode 215. Kth Largest Element in an Array
tags: [Queue, Heap, Priority Queue, Leetcode, Array]

---

## 題解

### MaxHeap (Priority Queue)

```python=
class Heap:
    def __init__(self):
        self.heap = []

    @property
    def length(self):
        return len(self.heap)

    def insert(self, val: int):
        self.heap.append(val)
        self.swin(self.length - 1)

    def pop(self):
        value = self.heap[0]
        self.swap(0, self.length - 1)
        self.heap.pop()
        self.sink(0)
        return value

    def parent(self, k):
        return (k - 1) // 2

    def swap(self, m: int, n: int):
        self.heap[m], self.heap[n] = self.heap[n], self.heap[m]


class MaxHeap(Heap):
    def swin(self, k: int):
        while k > 0 and self.heap[self.parent(k)] < self.heap[k]:
            self.swap(self.parent(k), k)
            k = self.parent(k)

    def sink(self, k: int):
        while k * 2 + 1 < self.length:
            left, right = k * 2 + 1, k * 2 + 2
            target = left
            if right < self.length and self.heap[left] < self.heap[right]:
                target = right
            if self.heap[k] >= self.heap[target]:
                break
            self.swap(k, target)
            k = target


class MinHeap(Heap):
    def swin(self, k: int):
        while k > 0 and self.heap[self.parent(k)] > self.heap[k]:
            self.swap(self.parent(k), k)
            k = self.parent(k)

    def sink(self, k: int):
        while k * 2 + 1 < self.length:
            left, right = k * 2 + 1, k * 2 + 2
            target = left
            if right < self.length and self.heap[left] > self.heap[right]:
                target = right
            if self.heap[k] <= self.heap[target]:
                break
            self.swap(k, target)
            k = target

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        max_heap = MaxHeap()
        for num in nums:
            max_heap.insert(num)
        output = 0
        for i in range(k):
            output = max_heap.pop()
        return output
```