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)
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 56. Merge Intervals [Python] (0) | 2022.10.17 |
---|---|
LeetCode - 148. Sort List [Python] (0) | 2022.10.17 |
LeetCode - 105. Construct Binary Tree from Preorder and Inorder Traversal [Python] (0) | 2022.09.11 |
LeetCode - 783. Minimum Distance Between BST Nodes [Python] (0) | 2022.09.05 |
LeetCode - 938. Range Sum of BST [Python] (0) | 2022.09.03 |