Kth smallest element in sorted matrix

后端 未结 9 2192
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 14:43

This is an interview question.

Find the Kth smallest element in a matrix with sorted rows and columns.
Is it correct that the Kth small

9条回答
  •  攒了一身酷
    2020-12-23 15:35

    Start traversing the matrix from the top-left corner (0,0) and use a binary heap for storing the "frontier" - a border between a visited part of the matrix and the rest of it.

    Implementation in Java:

    private static class Cell implements Comparable {
    
        private final int x;
        private final int y;
        private final int value;
    
        public Cell(int x, int y, int value) {
            this.x = x;
            this.y = y;
            this.value = value;
        }
    
        @Override
        public int compareTo(Cell that) {
            return this.value - that.value;
        }
    
    }
    
    private static int findMin(int[][] matrix, int k) {
    
        int min = matrix[0][0];
    
        PriorityQueue frontier = new PriorityQueue<>();
        frontier.add(new Cell(0, 0, min));
    
        while (k > 1) {
    
            Cell poll = frontier.remove();
    
            if (poll.y + 1 < matrix[poll.x].length) frontier.add(new Cell(poll.x, poll.y + 1, matrix[poll.x][poll.y + 1]));
            if (poll.x + 1 < matrix.length) frontier.add(new Cell(poll.x + 1, poll.y, matrix[poll.x + 1][poll.y]));
    
            if (poll.value > min) {
                min = poll.value;
                k--;
            }
    
        }
    
        return min;
    
    }
    

提交回复
热议问题