题解 | #二维数组中的查找#
二维数组中的查找
http://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e
class Solution { public: bool Find(int target, vector<vector > array) {
/*
//方法一:列二分法
int row=array.size();
if(row<=0)
return false;
int rol=array[0].size();
//int rowbegin=0,rowend=row-1;
int rolbegin=0,rolend=rol-1;
for(int i=0;i<row;i++)
{
while(rolbegin<=rolend)
{
int mid=rolbegin+(rolend-rolbegin)/2;
if(array[i][mid]==target)
return true;
else if(array[i][mid]<target)
{
rolbegin=mid+1;
}
else
{
rolend=mid-1;
}
}
rolbegin=0;
rolend=rol-1;
}
return false;
*/
//方法二:分治
int row=array.size();
if(row<=0)
return false;
int rol=array[0].size();
int m=row-1,n=0;
while(m>=0&&n<rol)
{
if(array[m][n]==target)
return true;
else if(target<array[m][n])
{
m--;
}
else
{
n++;
}
}
return false;
}
};