Learn-dsa..in 30 days!



























CC-8 : Find Kth largest number in a matrix.

Description:

Given an array of integers as input matrix, find the kth largest number within the same.

Test cases and expected outputs:

Input Parameters Expected outputs
The input matrix :
11,32,93,
4,56,90,
5,51,94,
3rd largest element in Matrix: 90

Pseudocode:

We get matrix 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 max Heap. Provide Collections.reverseOrder() as argument to constructor of PriorityQueue, so that it acts as a max Heap.
Iterate though nums rowwise from index 0 to index row.length-1:
Add nums[rowIdx][colIdx]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 matrix.

Code:

public int findKthLargestInMatrix(int[][] nums, int k) {
	
	PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(Collections.reverseOrder());
	for (int iIdx=0; iIdx < nums.length; iIdx++) {
		for (int jIdx=0; jIdx < nums.length; jIdx++) {
			maxHeap.add(nums[iIdx][jIdx]);
		}
		if (maxHeap.size() > k) {
			maxHeap.remove();
		}
		
	}
	return (int) maxHeap.element();
}

Click here to download and run code and test cases !