Write an efficient algorithm, searches for a value in a m x n matrix. This matrix has the following properties:
Integers in each row is sorted in ascending from left to right. Integers in each column is sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, one, a],
[2, 5, 8, 3, 6, 9, +, + ],
[10, 13, 14, 17, 24], [approx., +, +, +
]
]
Given Target = 5, return true.
Given Target =, return false.
This is basically the same as the search 2D matrix, but now each column is ordered and can be searched from the lower-left or upper-right corners.
Lower left corner:
Class Solution {public
:
bool Searchmatrix (vector<vector<int>>& matrix, int target) {
int rows = Matrix.size ();
if (rows<=0)
return false;
int cols = Matrix[0].size ();
int i = rows-1;
int j = 0;
while (i>=0 && j<cols) {
if (matrix[i][j] = = target)
return true;
else if (matrix[i][j]<target)
j + +;
else
i--;
}
return false;
}
};
upper right Corner:
Class Solution {public
:
bool Searchmatrix (vector<vector<int>>& matrix, int target) {
int rows = Matrix.size ();
if (rows<=0)
return false;
int cols = Matrix[0].size ();
int i=0, j=cols-1;
while (i<rows && j>=0)
{
int x = matrix[i][j];
if (x = = target)
{
return true;
} else if (x >target)
{
j--;
} else{
i++;
}
}
return false;
}
};