首页 > 其他 > 详细

LeetCode-Kth Smallest Element in a Sorted Matrix

时间:2016-08-09 02:12:20      阅读:336      评论:0      收藏:0      [点我收藏+]

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.

Solution:

 1 public class Solution {
 2     public class ValuePair {
 3         int val;
 4         int x;
 5         int y;
 6         public ValuePair(int v, int i, int j){
 7             val = v;
 8             x = i;
 9             y = j;
10         }
11     }
12     public int kthSmallest(int[][] matrix, int k) {
13         if (matrix.length==0 || matrix[0].length==0) return -1;
14         
15         PriorityQueue<ValuePair> q = new PriorityQueue<ValuePair>((a,b) -> (a.val-b.val));
16         
17         for (int i=0;i<matrix.length;i++){
18             ValuePair p = new ValuePair(matrix[i][0],i,0);
19             q.add(p);
20         }
21         
22         ValuePair peek = null;
23         for (int i=0;i<k-1;i++){
24             peek = q.poll();
25             peek.y++;
26             if (peek.y<matrix[0].length){
27                 peek.val = matrix[peek.x][peek.y];
28                 q.add(peek);
29             }
30         }
31         peek = q.poll();
32         return peek.val;
33     }
34 }

 

LeetCode-Kth Smallest Element in a Sorted Matrix

原文:http://www.cnblogs.com/lishiblog/p/5751581.html

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