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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
/*class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size(), cols = 0;
if(rows == 0) return false;
cols = matrix[0].size();
if(target > matrix[rows-1][cols-1] || target < matrix[0][0]) return false;
int l = 0, r = rows-1;
while(l <= r) {
int mid = (l+r)/2;
if(matrix[mid][0] == target) return true;
else if(matrix[mid][0] > target) {
r=mid-1;
} else {
l = mid+1;
}
}
int row=l-1;
if(matrix[row][0] > target) row -= 1;
l=0;
r=cols-1;
while(l <= r) {
int mid = (l+r)/2;
if(matrix[row][mid] == target) return true;
else if(matrix[row][mid] > target) {
r = mid-1;
} else {
l = mid+1;
}
}
return false;
}
}*/
//n*m matrix convert to an array, matrix[x][y] arr[x*m+y]
//an array convert to n*m matrix, a[x] matrix[x/m][x%m]
class Solution {
public:
bool searchMatrix(vector<vector<int>> &matrix, int target) {
int n = matrix.size();
int m = matrix[0].size();
int l=0,r=m*n-1;
if(target>matrix[n-1][m-1] || target < matrix[0][0]) return false;
while(l<=r) {
int mid = (l+r)/2;
if(matrix[mid/m][mid%m] == target) return true;
else if(matrix[mid/m][mid%m] > target) {
r=mid-1;
} else {
l=mid+1;
}
}
return false;
}
}