每天两道算法题
题目
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
遍历解法
bool Find(int target, vector<vector<int> > array)
{
int len = array.size();
for( int i=0; i<len; ++i ) {
vector<int>::iterator end = array[i].end();
for( vector<int>::iterator pos=array[i].begin(); pos!=end; ++pos ) {
if( *pos == target ) return true;
else if ( *pos > target ) break;
}
}
return false;
}
最小时间复杂度
bool Find(int target, vector<vector<int> > array)
{
int row = array.size();
int col = array[0].size();
int x = 0;
int y = row - 1;
while( x>=0 && x<col && y>=0 && y<row ) {
if( array[y][x] == target ) return true;
else if( array[y][x] > target ) y--;
else x++;
}
return false;
}