https://leetcode.com/problems/kth-largest-element-in-an-array/

 

Kth Largest Element in an Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 


풀이 과정

배열에서 K번째 큰 원소를 반환하는 문제이다.

 

내림차순 정렬 후 K번째 원소를 찾아서 반환해주거나, 리스트를 힙으로 변환해 준 후, K번째 큰 원소가 나오도록 pop을 여러번 반복해주면 된다.


소스 코드

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        return sorted(nums, reverse=True)[k-1]

 

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        heapq.heapify(nums)
        length = len(nums)
        for _ in range(length - k):
            heapq.heappop(nums)
        return heapq.heappop(nums)

+ Recent posts