Coding Test/Python

[LeetCode] 215. Kth Largest Element in an Array(medium, python)

lim.dev 2024. 1. 5. 01:10

https://leetcode.com/problems/kth-largest-element-in-an-array/?envType=study-plan-v2&envId=top-interview-150

 

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)