Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Latest commit

 

History

History
executable file
·
26 lines (17 loc) · 1.11 KB

File metadata and controls

executable file
·
26 lines (17 loc) · 1.11 KB

378. Kth Smallest Element in a Sorted Matrix

Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

I remember I have done this work before. Binary search in a matrix.

STD use binary search to compute the number of nodes that is less than current number.

Thus, current value also need to be binary searched. Thus, the answer is binary search too.

to count the numbers:

while (i >= 0 && j < n) { if (matrix[i][j] <= target) { res += i + 1; ++j; } else { --i; } }

in this problem, because ++j means in the below rows current one < this one that means above column is smaller than current one which means all above colmn can be computed. (+= i + 1; ) and we count it by each column, we find the current one smaller column. Strictly, there we use brute force. We do not use binary search. We compare the last one not the middle one.

Thus, it's NlogN not loglogN.