Skip to content

Instantly share code, notes, and snippets.

@HDegano
Created May 27, 2015 15:19
Show Gist options
  • Save HDegano/bb3b235dc7f3fa571b45 to your computer and use it in GitHub Desktop.
Save HDegano/bb3b235dc7f3fa571b45 to your computer and use it in GitHub Desktop.
Search 2D Matrix where row and columns are sorted. Last item in row is less than the first item for the next row
public class Solution {
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