Skip to content

Instantly share code, notes, and snippets.

@HDegano
Created May 24, 2015 00:19
Show Gist options
  • Save HDegano/caff6c589409a469cbdb to your computer and use it in GitHub Desktop.
Save HDegano/caff6c589409a469cbdb to your computer and use it in GitHub Desktop.
Find item in sorted matrix where last number of each row is not greater than the first item of the next row.
public class Search2DMatrix{
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
if(rows <= 0) return false;
int cols = matrix[0].length;
if(cols <= 0) return false;
int lo = 0;
int hi = rows * cols - 1;
while(lo <= hi){
int mid = lo + (hi - lo)/2;
int midRow = mid / cols;
int midCol = mid % cols;
if(matrix[midRow][midCol] == target) return true;
else if(matrix[midRow][midCol] < target)
lo = mid + 1;
else hi = mid - 1;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment