Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

378 add Binary Search solution #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 20, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/main/java/com/fishercoder/solutions/_378.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,29 @@ public int kthSmallest(int[][] matrix, int k) {
}

//TODO: use heap and binary search to do it.

//Binary Search : The idea is to pick a mid number than 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, 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, 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;
}
}