adding a pq problem

This commit is contained in:
Jidong Xiao
2023-11-14 00:47:32 -05:00
parent 88ffa4e8b5
commit 27844c5e51
2 changed files with 20 additions and 1 deletions

View File

@@ -123,7 +123,7 @@ Lambda is new to the C++ language (part of C++11). But lambda is a core piece of
## 22.8 Leetcode Exercises
- [Leetcode problem 215: Kth Largest Element in an Array](https://leetcode.com/problems/rearrange-words-in-a-sentence/). Solution: [p1451_rearrange_words_in_a_sentence.cpp](../../leetcode/p1451_rearrange_words_in_a_sentence.cpp).
- [Leetcode problem 215: Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/). Solution: [p215_kth_largest_element.cpp](../../leetcode/p215_kth_largest_element.cpp).
- [Leetcode problem 373: Find K Pairs with Smallest Sums](https://leetcode.com/problems/most-frequent-subtree-sum/). Solution: [p508_most_frequent_subtree_sum.cpp](../../leetcode/p508_most_frequent_subtree_sum.cpp).
- [Leetcode problem 692: Top K Frequent Words](https://leetcode.com/problems/implement-stack-using-queues/). Solution: [p225_stack_using_queues.cpp](../../leetcode/p225_stack_using_queues.cpp).
- [Leetcode problem 912: Sort an Array](https://leetcode.com/problems/implement-queue-using-stacks/). Solution: [p232_queue_using_stacks.cpp](../../leetcode/p232_queue_using_stacks.cpp).

View File

@@ -0,0 +1,19 @@
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int ans;
int size = nums.size();
std::priority_queue<int> pq;
for(int i=0;i<size;i++){
// maintain a max heap
pq.push(nums[i]);
}
while(k>1){
// pop out k-1 times
pq.pop();
k--;
}
ans = pq.top();
return ans;
}
};