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.
解法:
把matrix当做一个array
n * m matrix convert to an array => matrix[x][y] => a[x * m + y]
an array convert to n * m matrix => a[x] =>matrix[x / m][x % m];
class Solution {
public:
bool searchMatrix(vector
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
searchMatrix(matrix,target,0,matrix.size()-1);
}
bool searchMatrix(vector<vector<int>>& matrix,int target,int start,int end)
{
if(end==start)return binarySearch(matrix[end],target);
if(end<start)return false;
int mid=(end+start)/2+1;
if(target>=matrix[mid][0])return searchMatrix(matrix,target,mid,end);
else{return searchMatrix(matrix,target,start,mid-1);}
}
bool binarySearch(vector<int>& v,int target)
{
return binarySearch(v,target,0,v.size()-1);
}
bool binarySearch(vector<int>& v,int target,int start,int end)
{
if(start==end){return target==v[start];}
int mid=(start+end)/2;
if(v[mid]==target)return true;
if(v[mid]>target){return binarySearch(v,target,start,mid);}
else{return binarySearch(v,target,mid+1,end);}
}
};