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
"""
'알고리즘 > LeetCode' 카테고리의 다른 글
LeetCode 212. Word Search II (0) | 2023.09.12 |
---|---|
LeetCode 373. Find K Pairs with Smallest Sums (python) (0) | 2023.09.12 |
LeetCode 211. Design Add and Search Words Data Structure (python) (0) | 2023.09.12 |
LeetCode 208. Implement Trie (Prefix Tree) (python) (0) | 2023.09.11 |
LeetCode 637. Average of Levels in Binary Tree (python) (0) | 2023.09.08 |