Created
May 27, 2015 15:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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