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.
Example:
Consider the following matrix:
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ]
Given target = 5, return true.
Given target = 20, return false.
So the difficulty is to reduce the search times by tricks and the method we chose is to start with left-bottom corner, since the 2-D array is sorted in ascending both from left to right and from top to bottom. That means the left-bottom corner (or right-top corner) is the "middle" of this array.
everytime we check the current value with target, and we then move the pointer. if the pointer goes beyond the bondaries or the number isnot found we return false, if we find the target we return true.
java code:
public static boolean searchMatrix(int[][] matrix,int target){
//first to check if empty, for 2-d array, a tricky one
if(matrix.length==0 || (matrix.length==1 && matrix[0].length==0)) return false;
// since starting with left-bottom corner
int row = matrix.length, i = row-1;
int col = matrix[0].length, j = 0;
while(i>=0 && i<=row-1 && j>=0 && j<=col-1){
int curvalue = matrix[i][j];
if(curvalue > target) i--;
else if(curvalue < target) j++;
else return true;
}
return false;
}
note that starting with the right-top corner also works, but the corresponding operation should be:
if(curvalue > target) j--;
else if (curvalue < target) i++;
since you start with the position and there's nowhere for row to minus or for column to add.
also:
when 2-d array in java is like:
a = {{}};
that will give you a.length==1 and a[0].length==0
some useful tips:
int[][] arr; arr == null
int[][] arr = {}; arr.length == 0
int[][] arr = {{}}; arr.length == 1 && arr[0].length == 0
int[][] arr = {{}, {}}; arr[0].length == 0 && arr[1].length == 0
.....
int[][] arr = {{}, null}; (arr[0] == null || arr[0].length == 0) && (arr[1] == null && arr[1].length == 0)