Complete the code to create a min heap from the vector.
std::priority_queue<int, std::vector<int>, [1]> minHeap(nums.begin(), nums.end());The min heap in C++ priority_queue is created by using std::greater<int> as the comparison function.
Complete the code to pop the smallest element from the min heap.
minHeap.[1]();Use pop() to remove the top (smallest) element from the priority_queue.
Fix the error in the code to get the kth smallest element from the min heap.
for (int i = 1; i < [1]; ++i) { minHeap.pop(); } return minHeap.top();
We pop (k-1) times to remove the first (k-1) smallest elements, then the top is the kth smallest. The loop runs from 1 to k-1, so condition is i < k.
Fill both blanks to complete the function that returns the kth smallest element using a min heap.
int kthSmallest(std::vector<int>& nums, int k) {
std::priority_queue<int, std::vector<int>, [1]> minHeap(nums.begin(), nums.end());
for (int i = 1; i < [2]; ++i) {
minHeap.pop();
}
return minHeap.top();
}i < k-1 pops too few elements.The min heap uses std::greater<int>. The loop runs while i < k to pop (k-1) elements.
Fill all three blanks to create a function that returns the kth smallest element using a min heap and handles empty input.
int kthSmallest(std::vector<int>& nums, int k) {
if (nums.empty() || k > nums.size()) return -1;
std::priority_queue<int, std::vector<int>, [1]> minHeap(nums.begin(), nums.end());
for (int i = 1; i < [2]; ++i) {
minHeap.[3]();
}
return minHeap.top();
}Use std::greater<int> for min heap, loop until i < k, and call pop() to remove elements.