378. Kth Smallest Element in a Sorted Matrix
by Botao Xiao
378. Kth Smallest Element in a Sorted Matrix
Question
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Note:
- You may assume k is always valid, 1 ≤ k ≤ n2.
Solution
- Method 1: PriorityQueue O(NlgN + K)
class Solution { public int kthSmallest(int[][] matrix, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for(int[] mat : matrix) for(int m : mat) pq.offer(m); while(--k != 0) pq.poll(); return pq.peek(); } }
- Method 2: binary search
class Solution { public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int low = matrix[0][0], high = matrix[n - 1][n - 1]; while(low <= high){ int mid = low + (high - low) / 2; int count = getLowerNum(matrix, mid); if(count < k) low = mid + 1; else high = mid - 1; } return low; } private int getLowerNum(int[][] matrix, int num){ int n = matrix.length; int row = n - 1, col = 0; int res = 0; while(row >= 0 && col < n){ if(matrix[row][col] > num) row--; else{ res += row + 1; col++; } } return res; } }
Subscribe via RSS