File tree 1 file changed +25
-0
lines changed
src/main/java/com/fishercoder/solutions
1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -37,4 +37,29 @@ public int kthSmallest(int[][] matrix, int k) {
37
37
}
38
38
39
39
//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
+ }
40
65
}
You can’t perform that action at this time.
0 commit comments