Intermediate Level
Implement the kthLargestElementHeap method that returns the kth largest value using heap logic.
The input array nums contains size integers, and k specifies the required position.
Your task is to return the kth largest element in the array. The value is based on sorted order, not on distinct values.
For example, in [3,2,1,5,6,4] with k = 2, the second largest element is 5.
Example 1
Input
nums (int[]) =
[3,2,1,5,6,4]size (int) =
6k (int) =
2Returns (int)
5Example 2
Input
nums (int[]) =
[3,2,3,1,2,4,5,5,6]size (int) =
9k (int) =
4Returns (int)
4Example 3
Input
nums (int[]) =
[1]size (int) =
1k (int) =
1Returns (int)
1Use a min heap of size k.
Insert values into the heap. If the heap size becomes greater than k, remove the smallest value from the heap. This keeps only the largest k values seen so far.
After all values are processed, the top of the min heap is the kth largest element.
Pseudocode:
function kthLargestElementHeap(nums, size, k):
create empty minHeap
for each value in nums:
push value into minHeap
if heap size > k:
remove smallest value from minHeap
return top of minHeapReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run