Kth Largest Element in an Array - LeetCode
Can you solve this real interview question? Kth Largest Element in an Array - Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct eleme
leetcode.com
아이디어
힙 자료구조를 사용해서 풀었다.
heapq 라이브러리는 최소힙만 제공하기 때문에 heappush 할 때 -를 붙여 음수로 만들어주었다.
그 후 K-1만큼 heappop해준 후, 마지막 k번째 데이터를 return 할 때 다시 -를 붙여 양수로 바꿔준다.
전체 코드
import heapq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = []
for num in nums:
heapq.heappush(heap, -num)
for _ in range(1, k):
heapq.heappop(heap)
return -heapq.heappop(heap)
'Coding Test > Python' 카테고리의 다른 글
[백준] 17140번: 이차원 배열과 연산 (골드4, 파이썬) (0) | 2024.01.06 |
---|---|
[백준] 17144번: 미세먼지 안녕! (골드4, 파이썬) (1) | 2024.01.05 |
[백준] 16236번: 아기 상어 (골드3, 파이썬) (0) | 2024.01.04 |
[LeetCode] 228. Summary Ranges (easy, python) (0) | 2024.01.04 |
[백준] 15686번: 치킨 배달(골드5, 파이썬) (0) | 2024.01.04 |