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


在一个排序矩阵中找从小到大的第 k 个整数。

排序矩阵的定义为:每一行递增,每一列也递增。

您在真实的面试中是否遇到过这个题?

Yes





样例

给出 k = 4 和一个排序矩阵:
[
  [1 ,5 ,7],
  [3 ,7 ,8],
  [4 ,8 ,9],
]


返回 5。

挑战

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



相关题目 Expand   

解题思路:

可以利用java自带的最小堆来进行每次选取最小的元素,一共选择K次就行了。

public class Solution {
     /**
     * @param matrix
     *            : a matrix of integers
     * @param k
     *            : an integer
     * @return: the kth smallest number in the matrix
     */
     class S {
          int row;
          int col;
          int val;
          public S(int row, int col, int val) {
               super();
               this.row = row;
               this.col = col;
               this.val = val;
          }

     }
     public int kthSmallest(int[][] matrix, int k) {
          // write your code here
          int m = matrix.length;
          if (0 == m)
               return -1;
          int n = matrix[0].length;
          PriorityQueue<S> queue = new PriorityQueue<S>(n,new MyComparators());
          for(int i=0;i<n;i++){
               queue.add(new S(0, i, matrix[0][i]));
          }
          for(int i=0;i<k-1;i++){
               S tmp = queue.poll();
               if(tmp.row<m-1){
                    queue.add(new S(tmp.row+1, tmp.col,matrix[tmp.row+1][tmp.col]));
               }              
          }
          return queue.poll().val;
     }
     @SuppressWarnings("unchecked") 
     class MyComparators implements Comparator<S> {
          @Override
          public int compare(S o1, S o2) {
               // TODO Auto-generated method stub
               if (o1.val > o2.val) {
                    return 1;
               } else if (o1.val == o2.val) {
                    return 0;
               } else {
                    return -1;
               }
          }

     }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值