378. 有序矩阵中第 K 小的元素

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


找的范围值矩阵中的最大值与最小值间的范围

    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;

        int l = matrix[0][0];
        int r = matrix[n-1][n-1];

        while(l<r) {
            int mid = l+(r-l)/2;
            if(find(matrix, mid) < k) {
                l = mid+1;
            } else {
                r= mid;
            }
        }
        return l;

    }

    public int find(int[][] matrix, int target) {

        int j=matrix.length-1;
        int count = 0;
        for(int i=0;i<matrix.length;i++) {
            while(j>=0 && matrix[i][j] > target) {
                j--;
                if(j< 0) {
                    return count;
                }
            }
            count += j+1;
        }
        return count;
    }

posted @ 2022-03-03 15:44  一颗青菜  阅读(0)  评论(0)    收藏  举报