378 Kth Smallest Element in a Sorted Matrix

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 ≤ n^2.

分析

和merge k sorted linked list是一样的,不同就是自己要打一个包建一个类,然后建一个pq

class Node{
    int x;
    int y;
    int val;
    public Node(int x, int y, int val) {
        this.x = x;
        this.y = y;
        this.val = val;
    }
}

public int kthSmallest(int[][] matrix, int k) {
    if(matrix.length == 0 || matrix[0].length == 0) {
        return 0;
    }
    int row = matrix.length;
    int col = matrix[0].length;
    PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>() {
        public int compare(Node n1, Node n2) {
            return n1.val - n2.val;
        }
    });
    for(int i = 0; i < matrix.length; i++) {
        pq.offer(new Node(i, 0,  matrix[i][0]));
    }
    while(k > 1) {
        Node node = pq.poll();
        k--;
        if(node.y < row - 1) {
            pq.offer(new Node(node.x, node.y + 1, matrix[node.x][node.y + 1]));
        }
    }
    return pq.poll().val;
}

时间复杂度是O(klogn). n = matrix.length


results matching ""

    No results matching ""