leetcode 378. Kth Smallest Element in a Sorted Matrix
这道题求有序矩阵中第K小的元素,数组如下:
二分的方法解决,时间复杂度: O(nlgX)。从左下角进行遍历
class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { int left = matrix[0][0],right = matrix.back().back(); while(left < right){ int mid = left + (right - left)/2; int index = search(matrix,mid); if(index < k) left = mid + 1; else right = mid; } return left; } int search(vector<vector<int>>& matrix,int target){ int i = matrix.size() - 1,j = 0,cnt = 0; while(i >= 0 && j < matrix[0].size()){ if(matrix[i][j] <= target){ j++; cnt += i + 1; } else i--; } return cnt; } };
https://www.cnblogs.com/grandyang/p/5727892.html