378. Kth Smallest Element in a Sorted Matrix
Medium
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Solution { int m, n; int[][] matrix; public int kthSmallest(int[][] matrix, int k) { m = matrix.length; n = matrix[0].length; this.matrix = matrix; int l = matrix[0][0], r = matrix[m-1][n-1]; while(l<r){ int m = (l+r)/2; if(valid(m, k)) r = m; else l = m+1; } return l; } //return true if #<=x is >=k boolean valid(int x, int k){ int cnt = 0; for(int i=0; i<m; ++i){ if(matrix[i][0]>x) break; for(int j=0; j<n; ++j){ if(matrix[i][j]<=x){ cnt++; if(cnt>=k) return true; }else break; } } return false; } } |
No comments:
Post a Comment