1. Topic description
In a two-dimensional array, 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.
2. Algorithm analysis
Since two-dimensional arrays are sorted, from left to right, from top to bottom, this feature can be used. Start traversing the target number from the last row, the first column. If the target number is greater than this number, continue to traverse the last row starting from the second column. If the target number is less than this number, then start traversing the penultimate row, and so on.
3. Code example
public boolean findTarget(int target, int [][] array) {
int i = array.length - 1;
int j = 0;
while(i >= 0 && j < array[i].length)
{
if(target < array[i][j])
{
i--;
}
else if(target > array[i][j])
{
j++;
}
else
{
return true;
}
}
return false;
}