Kth Smallest Element in Sorted Matrix

本文介绍了一种使用优先队列解决寻找矩阵中第K小元素的方法。通过定义一个内部类PayLoad并实现Comparable接口来比较值,此算法能够有效地找到指定大小的有序元素。
 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 }

 

转载于:https://www.cnblogs.com/shuashuashua/p/5745517.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值