-
Notifications
You must be signed in to change notification settings - Fork 77
/
_378_KthSmallestElementinaSortedMatrix.java
91 lines (79 loc) · 2.57 KB
/
_378_KthSmallestElementinaSortedMatrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package leetcode_1To300;
import java.util.PriorityQueue;
/**
* 本代码来自 Cspiration,由 @Cspiration 提供
* 题目来源:http://leetcode.com
* - Cspiration 致力于在 CS 领域内帮助中国人找到工作,让更多海外国人受益
* - 现有课程:Leetcode Java 版本视频讲解(1-900题)(上)(中)(下)三部
* - 算法基础知识(上)(下)两部;题型技巧讲解(上)(下)两部
* - 节省刷题时间,效率提高2-3倍,初学者轻松一天10题,入门者轻松一天20题
* - 讲师:Edward Shi
* - 官方网站:https://cspiration.com
* - 版权所有,转发请注明出处
*/
public class _378_KthSmallestElementinaSortedMatrix {
/**
* 378. Kth Smallest Element in a Sorted Matrix
* Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
min = 1 max = 15 mid = 8
1, PriorityQueue : 链表
2, Binary Search : 数个数
* @param matrix
* @param k
* @return
*/
// time : (nlogn) space : O(n)
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<Tuple> pq = new PriorityQueue<>(matrix.length, (a, b) -> (a.val - b.val));
for (int i = 0; i < matrix.length; i++) {
pq.offer(new Tuple(0, i, matrix[0][i]));
}
for (int i = 0; i < k - 1; i++) {
Tuple tuple = pq.poll();
if (tuple.x == matrix.length - 1) continue;
pq.offer(new Tuple(tuple.x + 1, tuple.y, matrix[tuple.x + 1][tuple.y]));
}
return pq.poll().val;
}
class Tuple {
int x, y, val;
public Tuple(int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
}
// time : O(n * log(max - min)) space : O(1)
public int kthSmallest2(int[][] matrix, int k) {
int n = matrix.length;
int left = matrix[0][0];
int right = matrix[n - 1][n - 1];
while (left + 1 < right) {
int mid = (right - left) / 2 + left;
int num = count(matrix, mid);
if (num >= k) right = mid;
else left = mid;
}
if (count(matrix, right) <= k - 1) return right;
return left;
}
private int count(int[][] matrix, int target) {
int n = matrix.length;
int res = 0;
int i = n - 1, j = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] < target) {
res += i + 1;
j++;
} else i--;
}
return res;
}
}