401.Kth Smallest Number in Sorted Matrix-排序矩阵中的从小到大第k个数(中等题)

排序矩阵中的从小到大第k个数

  1. 题目

    在一个排序矩阵中找从小到大的第 k 个整数。
    排序矩阵的定义为:每一行递增,每一列也递增。

  2. 样例

    给出 k = 4 和一个排序矩阵:
    这里写图片描述

  3. 挑战

    使用O(k log n)的方法,n为矩阵的宽度和高度中的最大值。

  4. 题解

    使用优先队列进行最小堆排序,每次选取最小的元素,第K次选择的就是第K大元素。

public class Solution {

    class Pair 
    {
        public int x, y, val;
        public Pair(int x, int y, int val) 
        {
            this.x = x;
            this.y = y;
            this.val = val;
        }
    }
    /**
     * @param matrix: a matrix of integers
     * @param k: an integer
     * @return: the kth smallest number in the matrix
     */
    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 Comparator<Pair>()
        {
            public int compare(Pair a, Pair b) 
            {
                return a.val - b.val;
            }
        });
        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];
                if(next_x < n && next_y < m && !hash[next_x][next_y])
                {
                    hash[next_x][next_y] = true;
                    Pair next_Pair = new Pair(next_x, next_y, matrix[next_x][next_y]);
                    minHeap.add(next_Pair);
                }
            }
        }
        return minHeap.peek().val;
    }
}

Last Update 2016.11.15

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值