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
.
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
// find if matrix == null or length is 0
if(matrix == null || matrix.length==0){
return false;
}
// find if matrix[0] == null or length is 0
if(matrix[0]==null || matrix[0].length ==0){
return false;
}
int row_end = matrix.length-1;
int column_end = matrix[0].length-1;
if(matrix[0][0]>target || matrix[row_end][column_end]< target){
return false;
}
int row_cur = row_end;
int column_cur = 0;
//start from last row and first column
//if last row and first column is larger than target, move to the last row
//if last row and first column is less than target, move to the next column
while(row_cur>=0 && column_cur<matrix[0].length){
if(matrix[row_cur][column_cur]>target){
row_cur--;
}
else if(matrix[row_cur][column_cur]<target){
column_cur++;
}
else if(matrix[row_cur][column_cur]==target){
return true;
}
}
return false;
}
}