给定一个二维数组,二维数组的规则如下:从上到下,从左到右,二维数组的元素顺序都是从小到大。
选用右上角查询的方法,可以知道如果查询目标比右上角的小,那么它必定在右上角的左边位置,如果比右上角的大,那么必定在右上角的下面位置。
public static Boolean arrayquery(int[,] nums, int target )
{
int rowlength = nums.GetLength(0);
int collength = nums.GetLength(1);
//右上角元素
int row = 0;int col = collength - 1;
while (row < rowlength && col >= 0)
{
if (target < nums[row, col])
{
col--;
}else if (target > nums[row, col])
{
row++;
}else if (target==nums[row,col])return true;
}
return false;
}