378. Kth Smallest Element in a Sorted Matrix

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

 

Note: 
You may assume k is always valid, 1 ≤ k ≤ n2.

 1 public class Solution {
 2     public int kthSmallest(int[][] matrix, int k) {
 3         int n = matrix.length;
 4         PriorityQueue<Wrapper> pq = new PriorityQueue<Wrapper>();
 5         for(int i=0;i<n;i++) pq.offer(new Wrapper(0,i,matrix[0][i]));
 6         for(int i=0;i<k-1;i++){
 7             Wrapper w = pq.poll();
 8             int x = w.x;
 9             if(x==n-1) continue;
10             pq.offer(new Wrapper(x+1,w.y,matrix[x+1][w.y]));
11         }
12         return pq.poll().val;
13     }
14     class Wrapper implements Comparable<Wrapper>{
15         int x;
16         int y;
17         int val;
18         public Wrapper(int x,int y,int val){
19             this.x = x;
20             this.y = y;
21             this.val = val;
22         }
23         public int compareTo(Wrapper that){
24             return this.val-that.val;
25         }
26     }
27 }
28 //the run time complexity could be O(klongn), the space complexity could be O(k);
 1 public class Solution {
 2     public int kthSmallest(int[][] matrix, int k) {
 3         int left = matrix[0][0];
 4         int right = matrix[matrix.length-1][matrix.length-1]+1;
 5         while(left<right){
 6             int mid = left +(right-left)/2;
 7             int count = 0;
 8             int j = matrix.length-1;
 9             for(int i=0;i<matrix.length;i++){
10                 while(j>=0&&matrix[i][j]>mid){
11                     j--;
12                 }
13                 count+=j+1;
14             }
15             if(count<k) left = mid+1;
16             else right = mid;
17         }
18         return left;
19     }
20 }
21 //the run time complexity could be O()???

 

转载于:https://www.cnblogs.com/codeskiller/p/6939468.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值