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

LeetCode-Kth Smallest Element in a Sorted Matrix

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