https://leetcode.com/problems/kth-largest-element-in-an-array/description
Kth Largest Element in an Array - LeetCode
Can you solve this real interview question? Kth Largest Element in an Array - 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 eleme
leetcode.com
Q. 해당 주어진 배열에서 k 번째로 큰 원소를 반환하라.
Solution.
Max Heap을 사용.
int findKthLargest(vector<int>& nums, int k)
{
priority_queue<int> pqBuff;
for (int k = 0; k < nums.size(); ++k)
{
pqBuff.push(nums[k]);
}
while (!pqBuff.empty())
{
int top = pqBuff.top();
--k;
if (k == 0)
return top;
pqBuff.pop();
}
return -1;
}
stl::sort()를 사용한 것은 아니지만, 선 구현된 자료구조를 사용했다.
문제의 취지에 맞는지 조금은 애매하다.
다른 풀이법도 알아 두면 좋을 듯.
'Leetcode > LeetCode75' 카테고리의 다른 글
[Heap/Priority Queue][Medium] 2542. Maximum Subsequence Score (1) | 2024.01.06 |
---|---|
[Heap/Priority Queue][Medium] 2336. Smallest Number in Infinite Set (1) | 2024.01.03 |
[Binary Search Tree][Medium] 450. Delete Node in a BST (1) | 2023.12.31 |
[Binary Search Tree][Easy] 700. Search in a Binary Search Tree (1) | 2023.12.30 |
[Binary Tree-BFS][Medium] 1161. Maximum Level Sum of a Binary Tree (1) | 2023.12.28 |