题目内容:
有一个数字矩阵,矩阵的每行从左到右是递增的,从上到下是递增的,
请编写程序在这样的矩阵中查找某个数字是否存在。
int Find(int arr[][5], int row, int col, int target)
{
//查找的本质:排除的过程
//从右上角开始比较,一次可以排除一行,或者一列
int i = 0;
int j = col - 1;
while (i < row&&j >= 0)
{
if (target < arr[i][j])
{
--j;
}
else if (target > arr[i][j])
{
++i;
}
else {
return 1;
}
}
return -1;
}
int main()
{
int arr[][5] = {
{1, 2, 3, 4, 5},
{11, 22, 33, 44, 55},
{111,222,333,444,555}
};
int x = 333;
int ret = Find(arr, 3, 5, x);
printf("%d\n",ret);
system("pause");
return 0;
}
加油吧 阿超没有蛀牙!