[LeetCode] Kth Largest Element in an Array

yoonene·2023년 3월 21일
0

알고리즘

목록 보기
62/62

문제 이동

힙으로 풀기

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

정렬로 풀기

python의 정렬은 빠르기 때문에 웬만하면 정렬로 푸는 게 좋을 듯

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        return sorted(nums, reverse=True)[k-1]
profile
NLP Researcher / Information Retrieval / Search

0개의 댓글