Given an n x n matrix where each of the rows and columns is 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.
You must find a solution with a memory complexity better than O(n2).
Time : (logn)
Space : O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intkthSmallest(vector<vector<int>>& matrix, int k){ int l = matrix[0][0], r = matrix.back().back(), n = matrix.size(); while(l < r) { int m = l + (r - l) / 2, cnt = 0; for(int i = 0; i < n; i++) { cnt += upper_bound(matrix[i].begin(), matrix[i].end(), m) - matrix[i].begin(); } if(cnt < k) l = m + 1; else r = m; } return l; } };