215. Kth Largest Element in an Array
정렬로 푸는 법
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
return nums[-k]
정렬 하지 않고 푸는 법
- Heap / Priority Queue 사용
- 힙 큐, 우선순위 큐
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = []
for n in nums:
heapq.heappush(heap, -n) # - 붙임으로써 큰->작은순으로 정렬
while k:
res = heapq.heappop(heap)
k-=1
return -res
참고:
https://littlefoxdiary.tistory.com/3
[Python] 힙 자료구조 / 힙큐(heapq) / 파이썬에서 heapq 모듈 사용하기
힙은 특정한 규칙을 가지는 트리로, 최댓값과 최솟값을 찾는 연산을 빠르게 하기 위해 고안된 완전이진트리를 기본으로 한다. 힙 property : A가 B의 부모노드이면 A의 키값과 B의 키값 사이에는 대
littlefoxdiary.tistory.com
'LeetCode > LeetCode75' 카테고리의 다른 글
| [LeetCode 75] Medium - 1926. Nearest Exit from Entrance in Maze (3) | 2024.11.19 |
|---|---|
| [LeetCode 75] Medium - 2336. Smallest Number in Infinite Set (0) | 2024.11.18 |
| [LeetCode 75] Medium - 1466. Reorder Routes to Make All Paths Lead to the City Zero (0) | 2024.11.18 |
| [LeetCode 75] Medium - 841. Keys and Rooms (0) | 2024.11.18 |
| [LeetCode 75] Medium - 1161. Maximum Level Sum of a Binary Tree (0) | 2024.11.17 |