首页 > 其他 > 详细

Kth Smallest Element in Sorted Matrix

时间:2016-08-07 09:36:27      阅读:206      评论:0      收藏:0      [点我收藏+]
 1 public class Solution {
 2     public int kthSmallest(int[][] matrix, int k) {
 3         if (matrix.length == 0 || matrix[0].length == 0 || k <= 0) {
 4             return -1;
 5         }
 6         PriorityQueue<PayLoad> queue = new PriorityQueue<>();
 7         for (int i = 0; i < matrix[0].length; i++) {
 8             queue.offer(new PayLoad(0, i, matrix[0][i]));
 9         }
10         PayLoad current = null;
11         for (int i = 0; i < Math.min(matrix.length * matrix[0].length, k); i++) {
12             current = queue.poll();
13             if (current.x == matrix.length - 1) {
14                 continue;
15             }
16             queue.offer(new PayLoad(current.x + 1, current.y, matrix[current.x + 1][current.y]));
17         }
18         return current.value;
19     }
20     
21     class PayLoad implements Comparable<PayLoad> {
22         private int x;
23         private int y;
24         private int value;
25         public PayLoad(int x, int y, int value) {
26             this.x = x;
27             this.y = y;
28             this.value = value;
29         }
30         
31         @Override
32         public int compareTo(PayLoad that) {
33             return this.value - that.value;
34         }
35     }
36 }

 

Kth Smallest Element in Sorted Matrix

原文:http://www.cnblogs.com/shuashuashua/p/5745517.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!