CC-3 : Find Kth largest number in an Array.
Description:
Given an array of integers as input array, find the kth largest number within the same.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| int[] nums= {3,4,7,9,10,15, 17, 21}; retVal=hp.findKthLargest(nums, 3); | 3rd largest num: 15 |
| int[] nums= {3,4,7,9,10,15, 17, 21}; retVal=hp.findKthLargest(nums, 6); | 6th largest num: 7 |
Pseudocode:
| We get array of integers nums as input parameter. We need to find kth largest num and value of k is also received as input parameter. |
| Initialize a PriorityQueue instance to be used as min Heap. |
| Iterate though nums from index 0 to index nums.length-1:
Add nums[idx]to PriorityQueue.
If PriorityQueue size is > k, remove the top element from PriorityQueue.
|
| Return top element of PriorityQueue, it is the k th largest element of the input array. |
Code:
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap=new PriorityQueue<Integer>();
for (int idx=0; idx < nums.length; idx++) {
minHeap.add(nums[idx]);
if (minHeap.size() > k) {
minHeap.remove();
}
}
return minHeap.element();
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |