码迷,mamicode.com
首页 > 其他好文 > 详细

Kth Smallest Element in Sorted Matrix

时间:2016-08-07 09:39:07      阅读:168      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!