Finding the kth largest element in a sorted matrix.
Here’s a Java program that finds the kth largest element in a sorted matrix:
import java.util.PriorityQueue; public class KthLargestElementInMatrix { public static int findKthLargest(int[][] matrix, int k) { int rows = matrix.length; int cols = matrix[0].length; // Use a max heap to store the k largest elements PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a); // Iterate through the matrix and add elements to the max heap for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { maxHeap.offer(matrix[i][j]); // If the heap size exceeds k, remove the smallest element if (maxHeap.size() > k) { maxHeap.poll(); } } } // The top element in the max heap is the kth largest element return maxHeap.peek(); } public static void main(String[] args) { int[][] matrix = { {1, 5, 9}, {10, 11, 13}, {12, 13, 15} }; int k = 8; int kthLargest = findKthLargest(matrix, k); System.out.println("The kth largest element in the matrix is: " + kthLargest); } }
In this program, we use a max heap (PriorityQueue) to store the k largest elements encountered in the matrix. We iterate through the matrix and add each element to the heap. If the heap size exceeds k, we remove the smallest element from the heap to maintain the k largest elements. Finally, the top element in the max heap is the kth largest element in the matrix.
In the provided example, the matrix is initialized with some values, and we find the 8th largest element. You can modify the matrix and the value of k in the `main` method to test different scenarios.
No comments yet! You be the first to comment.