Created
May 24, 2015 00:19
-
-
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.
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 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