其他分享
首页 > 其他分享> > LeetCode精选TOP面试题378.有序矩阵中第 K 小的元素

LeetCode精选TOP面试题378.有序矩阵中第 K 小的元素

作者:互联网

题目描述

example
input  : matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
output : 13
input  : matrix = [[-5]], k = 1
output : -5

解题思路

思路1 排序

思路2 二分查找

代码(Java)

思路1代码

public class Solution1 {
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        int[] array = new int[n * n];
        int t = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                array[t++] = matrix[i][j];
            }
        }
        Arrays.sort(array);
        return array[k - 1];
    }
}

思路2代码

public class Solution2 {
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        int left = matrix[0][0];
        int right = matrix[n - 1][n - 1];
        while (left < right) {
            int mid = left + ((right - left) >> 1);
            int count = findSmaller(matrix, mid, n);
            if (count < k) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return right;
    }

    private int findSmaller(int[][] matrix, int mid, int n) {
        int count = 0;
        int i = n - 1;
        int j = 0;
        while (i >= 0 && j < n) {
            if (matrix[i][j] <= mid) {
                count += i + 1;
                j++;
            } else {
                i--;
            }
        }
        return count;
    }
}

标签:count,面试题,right,matrix,int,TOP,元素,mid,378
来源: https://blog.csdn.net/flower_48237/article/details/122512568