Skip to content

Commit 8554e08

Browse files
xdongyanfishercoder1534
authored andcommitted
378 add Binary Search solution (#17)
* edit 279 * edit 322 * conflit * 378 add BS solution
1 parent b6ed089 commit 8554e08

File tree

1 file changed

+25
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+25
-0
lines changed

src/main/java/com/fishercoder/solutions/_378.java

+25
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,29 @@ public int kthSmallest(int[][] matrix, int k) {
3737
}
3838

3939
//TODO: use heap and binary search to do it.
40+
41+
//Binary Search : The idea is to pick a mid number than compare it with the elements in each row, we start form
42+
// 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
43+
// that less than mid and compare with k, then update the k.
44+
public int kthSmallestBS(int[][] matrix, int k) {
45+
int row = matrix.length - 1, col = matrix[0].length - 1;
46+
int lo = matrix[0][0];
47+
int hi = matrix[row][col] ;
48+
while(lo < hi) {
49+
int mid = lo + (hi - lo)/2;
50+
int count = 0, j = col;
51+
for(int i= 0; i <= row; i++) {
52+
while(j >=0 && matrix[i][j] > mid) {
53+
j--;
54+
}
55+
count += (j + 1);
56+
}
57+
if(count < k) {
58+
lo = mid + 1;
59+
} else {
60+
hi = mid;
61+
}
62+
}
63+
return lo;
64+
}
4065
}

0 commit comments

Comments
 (0)