알고리즘/LeetCode

LeetCode 215. Kth Largest Element in an Array (python)

Timha 2023. 9. 12. 01:16

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 element.

Can you solve it without sorting?

 

 

 

 

풀이

 

배열을 정렬하지 않고 k번째 큰 수를 출력하는 문제이다.

 

최대힙을 사용해서 문제를 풀 생각을 했고,  heapq를 사용해서 각 숫자들을 음수로 바꿔준 뒤 

 

pop을 k+1번 시행하여 답을 찾았다.

 

import heapq
def changeMinus(n):
        return -n
class Solution(object):
    def findKthLargest(self, nums, k):
        result = 0
        q= []
        for i in nums:
            heapq.heappush(q,-i)

        for __  in range(k):
            result = heapq.heappop(q)
        return -result
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """