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.
For 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
.
public class Solution {
public boolean search(int[][] matrix,int a, int b, int m, int n, int target) {
if(a > m || b > n) return false;
if(matrix[m][n] < target || matrix[a][b] > target) return false;
else if(matrix[m][n] == target || matrix[a][b] == target) return true;
else {
int left_top_row = a, left_top_column = b, right_buttom_row = m, right_buttom_column = n;
int low = left_top_column, high = right_buttom_column;
int row = left_top_row;
while (low <= high) {
int middle = (low + high)/2;
if (matrix[row][middle] == target) return true;
else if (matrix[row][middle] > target) {
high = middle-1;
} else {
low = middle+1;
}
}
if(low < right_buttom_column) {
n = low;
} else {
a += 1;
}
low = left_top_row;
high = right_buttom_row;
int column = left_top_column;
while (low <= high) {
int middle = (low+high)/2;
if (matrix[middle][column] == target) return true;
else if(matrix[middle][column] > target) high = middle-1;
else low = middle + 1;
}
if(low < right_buttom_row) {
m = low;
} else {
b += 1;
}
return search(matrix, a, b, m, n, target);
}
}
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n=matrix[0].length;
return search(matrix,0,0,m-1,n-1,target);
}
}