/*
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
*/
public boolean searchMatrix(int[][] matrix, int target) {
//ERROR CHECK:
//Matrix empty
if(matrix.length == 0 || matrix[0].length == 0) return false;
//Target not in matrix
int rows = matrix.length;
int columns = matrix[0].length;
if(target < matrix[0][0] || target > matrix[rows-1][columns-1]) return false;
int row = rows-1;
int column = 0;
while(row >= 0 && column < columns){
if(matrix[row][column] == target) return true;
else if(matrix[row][column] > target) row--;
else column ++;
}
return false;
}
/*
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
*/
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length == 0 || matrix[0].length == 0) return false;
int row = 0;
while(row < matrix.length && matrix[row][0] <= target){
if(matrix[row][0] == target) return true;
row++;
}
if(row == 0) return false;
if(Arrays.binarySearch(matrix[row-1], target) >= 0) return true;
else return false;
}