Tuesday, May 28, 2019

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.
Code (Java):
/*
 * @lc app=leetcode id=378 lang=java
 *
 * [378] Kth Smallest Element in a Sorted Matrix
 */
class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        if (matrix == null || matrix.length == 0 || k <= 0 || k > matrix.length * matrix.length) {
            return -1;
        }

        int n = matrix.length;

        PriorityQueue<Pair> minHeap = new PriorityQueue<>(new MyPairComparator());

        boolean[][] visited = new boolean[n][n];

        minHeap.offer(new Pair(0, 0, matrix[0][0]));
        visited[0][0] = true;

        Pair ans = null;
        int[][] dirs = {{0, 1}, {1, 0}};

        for (int i = 0; i < k; i++) {
            ans = minHeap.poll();
            for (int j = 0; j < 2; j++) {
                int nx = ans.x + dirs[j][0];
                int ny = ans.y + dirs[j][1];
                if (nx < n && ny < n && !visited[nx][ny]) {
                    minHeap.offer(new Pair(nx, ny, matrix[nx][ny]));
                    visited[nx][ny] = true;
                }
            }
        }

        return ans.val;
    }
}

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

class MyPairComparator implements Comparator<Pair> {
    @Override
    public int compare(Pair a, Pair b) {
        return a.val - b.val;
    }
}


No comments:

Post a Comment