Leetcode: 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.

Heap: you need to know the row number and column number of that element(so we can create a tuple class here)

 public class Solution {
public int kthSmallest(int[][] matrix, int k) {
Comparator<Tuple> comp = new Comparator<Tuple>() {
public int compare(Tuple tp1, Tuple tp2) {
return tp1.val - tp2.val;
}
}; PriorityQueue<Tuple> minHeap = new PriorityQueue<Tuple>(matrix.length, comp); int res = 0; for (int row=0; row<matrix.length; row++) {
minHeap.offer(new Tuple(row, 0, matrix[row][0]));
} for (int i=1; i<=k; i++) {
Tuple tp = minHeap.poll();
if (i == k) {
res = tp.val;
break;
}
if (tp.y < matrix.length-1) minHeap.offer(new Tuple(tp.x, tp.y+1, matrix[tp.x][tp.y+1]));
}
return res;
} public class Tuple {
int x;
int y;
int val;
public Tuple(int i, int j, int value) {
this.x = i;
this.y = j;
this.val = value;
}
}
}

Binary Search方法:(12/28仔细看了之后觉得没必要深究,有时间再去深究吧)

 public class Solution {
public int kthSmallest(int[][] matrix, int k) {
int lo = matrix[0][0], hi = matrix[matrix.length - 1][matrix[0].length - 1] + 1;//[lo, hi)
while(lo < hi) {
int mid = lo + (hi - lo) / 2;
int count = 0, j = matrix[0].length - 1;
for(int i = 0; i < matrix.length; i++) {
while(j >= 0 && matrix[i][j] > mid) j--;
count += (j + 1);
}
if(count < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
}

referred tohttps://discuss.leetcode.com/topic/52948/share-my-thoughts-and-clean-java-code/2

上一篇:ActiveMQ 的安装


下一篇:Python基础学习之常用模块