소프트웨어에 대한 모든 것

LeetCode 풀기 - 215. Kth Largest Element in an Array 본문

알고리즘/LeetCode

LeetCode 풀기 - 215. Kth Largest Element in an Array

앤테바 2022. 2. 24. 20:09
반응형

215. Kth Largest Element in an Array

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

문제)

솔루션1) sorted() 함수 사용

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

솔루션2) PriorityQueue 사용

from queue import PriorityQueue
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        q = PriorityQueue()
        [q.put(-n) for n in nums]
        [q.get() for i in range(k-1)]
        return -q.get()

 

함께 보면 좋은 글

2022.02.24 - [파이썬] - [파이썬] 우선순위큐(PriorityQueue) 사용법

2022.02.24 - [파이썬] - [파이썬] sorted() 정렬 함수 파헤치기

반응형
Comments