forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_378.java
55 lines (52 loc) · 1.77 KB
/
_378.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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class _378 {
public static class Solution1 {
/**
* brute force made it AC'ed, extreme test case needed for OJ
*/
public int kthSmallest(int[][] matrix, int k) {
List<Integer> list = new ArrayList();
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
list.add(matrix[i][j]);
}
}
Collections.sort(list);
return list.get(k - 1);
}
}
public static class Solution2 {
/**
* Binary Search : The idea is to pick a mid number, then compare it with the elements in each row, we start form
* end of row util we find the element is less than the mid, the left side element is all less than mid; keep tracking elements
* that less than mid and compare with k, then update the k.
*/
public int kthSmallestBS(int[][] matrix, int k) {
int row = matrix.length - 1;
int col = matrix[0].length - 1;
int lo = matrix[0][0];
int hi = matrix[row][col];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int count = 0;
int j = col;
for (int i = 0; i <= row; i++) {
while (j >= 0 && matrix[i][j] > mid) {
j--;
}
count += (j + 1);
}
if (count < k) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
}
}