378. Kth Smallest Element in a Sorted Matrix

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.






class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int lo = matrix[0][0];
        int hi = matrix[matrix.length - 1][matrix[0].length - 1];
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int count = numberOfLessAndEqualInMatrix(matrix, mid);
            if (count < k) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        
        return lo;
    }
    
    private int numberOfLessAndEqualInMatrix(int[][] matrix, int target) {
        int count = 0;
        int row = matrix.length - 1, col = 0;
        while (row >= 0 && col < matrix[0].length) {
            if (matrix[row][col] > target) {
                row--;
            } else {
                col++;
                count += row + 1;
            }
        }
        
        return count;
    }
    
    public int kthSmallestUsingHeap(int[][] matrix, int k) {
        List<Integer> list = new ArrayList<>();
        for (int[] row : matrix) {
            for (int num : row) {
                list.add(num);
            }
        }
        PriorityQueue<Integer> pq = new PriorityQueue<>(list);
        for (int i = 0; i < k - 1; i++) {
            pq.poll();
        }
        return pq.poll();
    }
}














class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
        for(int j = 0; j <= n-1; j++) pq.offer(new Tuple(0, j, matrix[0][j]));
        for(int i = 0; i < k-1; i++) {
            Tuple t = pq.poll();
            if(t.x == n-1) continue;
            pq.offer(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y]));
        }
        return pq.poll().val;
    }
}

class Tuple implements Comparable<Tuple> {
    int x, y, val;
    public Tuple (int x, int y, int val) {
        this.x = x;
        this.y = y;
        this.val = val;
    }
    
    @Override
    public int compareTo (Tuple that) {
        return this.val - that.val;
    }
}

 

以上是关于378. Kth Smallest Element in a Sorted Matrix的主要内容,如果未能解决你的问题,请参考以下文章

378. Kth Smallest Element in a Sorted Matrix

#Leetcode# 378. Kth Smallest Element in a Sorted Matrix

378. Kth Smallest Element in a Sorted Matrix

378. Kth Smallest Element in a Sorted Matrix

leetcode 378. Kth Smallest Element in a Sorted Matrix

Leetcode 378. Kth Smallest Element in a Sorted Matrix