Brush notes (1)-search in a two-dimensional array
topic
In a two-dimensional array (each one-dimensional array has the same length), each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer, and determine whether the array contains the integer.
Ideas
The array is incremented horizontally and vertically
The number in the lower left corner of the array is greater than the number on the column is smaller than the number on the row
So start the search from the bottom left corner, if the target is less than this number, search upwards along the column; if the target is greater than this number, search along the line change to the right
Code
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int row_size=array.size();
int col_size=array[0].size();
//从左下角开始
for(int i=row_size-1,j=0;i>=0&&j<col_size;)
{
if(target==array[i][j])
return true;
else if(target<array[i][j])//小于,则往上找
{
i--;
continue;
}
else//大于则向右找
{
j++;
continue;
}
}
return false;
}
};