Kth Smallest Number in Sorted Matrix

Description

Find the kth smallest number in a row and column sorted matrix.

Each row and each column of the matrix is incremental.

Example

Example 1:

Input:
[
  [1 ,5 ,7],
  [3 ,7 ,8],
  [4 ,8 ,9],
]
k = 4
Output: 5

Example 2:

Input:
[
  [1, 2],
  [3, 4]
]
k = 3
Output: 3

Challenge

O*(klogn*) time, n is the maximum of the width and height of the matrix.

思路:

可以使用堆或者二分在 O(klogn) 的时间复杂度内解决问题.

用堆解决:

定义一个小根堆, 起始仅仅放入第一行第一列的元素.

循环 kk 次, 每一次取出一个元素, 然后把该元素右方以及下方的元素放入堆中, 第 kk 次取出的元素即为答案.

其中, 要注意一个元素不能重复入堆, 需要记录.


二分法:

二分答案,初始区间即矩阵最小值和最大值构成的区间.

二分过程查找区间中点 mid 在矩阵中的排名, 假设为 t

  • 若 t == k, 该点即是结果
  • 若 t > k, 区间变成 [l, mid - 1]
  • 若 t < k, 区间变成 [mid + 1, r]
    public class Solution {
        /**
         * @param matrix: a matrix of integers
         * @param k: An integer
         * @return: the kth smallest number in the matrix
         */
         
        class Pair {
            public int x, y, val;
            public Pair(int x, int y, int val) {
                this.x = x;
                this.y = y;
                this.val = val;
            }
        }
        class PairComparator implements Comparator<Pair> {
            public int compare(Pair a, Pair b) {
                return a.val - b.val;
                }
        }
        public int kthSmallest(int[][] matrix, int k) {
            int[] dx = new int[]{0, 1};
            int[] dy = new int[]{1, 0};
            int n = matrix.length;
            int m = matrix[0].length;
            boolean[][] hash = new boolean[n][m];
            PriorityQueue<Pair> minHeap = new PriorityQueue<Pair>(k, new PairComparator());
            minHeap.add(new Pair(0, 0, matrix[0][0]));
    
            for (int i = 0; i < k - 1; i++) {
                Pair cur = minHeap.poll();
                for (int j = 0; j < 2; j++) {
                    int next_x = cur.x + dx[j];
                    int next_y = cur.y + dy[j];
                    Pair next_Pair = new Pair(next_x, next_y, 0);
                    if (next_x < n && next_y < m && !hash[next_x][next_y]) {
                        hash[next_x][next_y] = true;
                        next_Pair.val = matrix[next_x][next_y];
                        minHeap.add(next_Pair);
                    }
                }
            }
            return minHeap.peek().val;
        }
    }
    

      

猜你喜欢

转载自www.cnblogs.com/FLAGyuri/p/12078513.html
今日推荐