[LeetCode] 378. Kth Smallest Element in a Sorted Matrix

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

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

Example:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

 

Note: 
You may assume k is always valid, 1 ≤ k ≤ n2.

 

题意:给一个已经排好序的二维数组,找到第k小的数

注意,它不是蛇形有序的。

法一:使用堆,一边插一边删,保证堆只有k个元素就行了;

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        PriorityQueue<Integer> heap = new PriorityQueue<>(k + 1, (a, b) -> {
            if (a < b)
                return 1;
            if (a > b)
                return -1;
            else
                return 0;
        });
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++) {
                heap.add(matrix[i][j]);
                if (heap.size() > k)
                    heap.poll();
            }
        return heap.poll();
    }
}

法二:其实用法一有个特点,我们没有利用排好序的这个特点,换言之,随便给个二维数组,就可以实现,显然不可能是最高效的

既然想到是排好序的,那么又是查,我们就会想到二分的思想

class Solution {
    private int helper(int[][] matrix, int tar) {
        int n = matrix.length;
        int i = n - 1;
        int j = 0;
        int res = 0;
        while (i >= 0 && j < n) {
            if (matrix[i][j] <= tar) {
                res += i + 1;
                j++;
            } else {
                i--;
            }
        }
        return res;
    }
    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) / 2;
            int cnt = helper(matrix, mid);
            if (cnt < k)
                left = mid + 1;
            else
                right = mid;
        }
        return left;
    }
}

 

转载于:https://www.cnblogs.com/Moriarty-cx/p/9800363.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值