-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path378.java
More file actions
66 lines (64 loc) · 2.24 KB
/
378.java
File metadata and controls
66 lines (64 loc) · 2.24 KB
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
__________________________________________________________________________________________________
sample 0 ms submission
class Solution {
public int kthSmallest(int[][] matrix, int k) {
// use binaru search
// the array is not fully sorted
// but when we know lo and hi, we could always know how many entries
// are smaller than mid (in an efficient way), and redefine the search range
int row = matrix.length, col = matrix[0].length;
int lo = matrix[0][0], hi = matrix[row-1][col-1];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// now count how many entries are smaller than mid
// you may count row by row, or another way
int count = getLessOrEqual(matrix, mid);
if (count < k) lo = mid + 1;
else hi = mid;
}
// how can you make sure that lo is one of the elements in the matrix?
return lo;
}
private int getLessOrEqual(int[][] matrix, int target) {
// this function is very interesting!
// think about how it works!
int i = matrix.length - 1, j = 0;
int res = 0;
while (i >= 0 && j < matrix[0].length) {
if (matrix[i][j] > target) {
i --;
} else {
res += i + 1;
j++;
}
}
return res;
}
}
__________________________________________________________________________________________________
sample 38732 kb submission
class Solution {
public int kthSmallest(int[][] M, int k) {
int n = M.length;
PriorityQueue<Tuple> Q = new PriorityQueue<>(10000, (a, b) -> M[a.r][a.c] - M[b.r][b.c]);
Tuple t = new Tuple(0, 0);
Q.add(t);
while (k-- > 0) {
t = Q.remove();
if (t.r + 1 < n)
Q.add(new Tuple(t.r + 1, t.c));
if (t.r == 0 && t.c + 1 < n)
Q.add(new Tuple(t.r, t.c + 1));
}
return M[t.r][t.c];
}
class Tuple {
int r;
int c;
Tuple(int r, int c) {
this.r = r;
this.c = c;
}
}
}
__________________________________________________________________________________________________