杨氏矩阵
有一个数字矩阵,矩阵的每行从左到右是递增的,矩阵从上到下是递增的,请编写程序在这样的矩阵中查找某个数字是否存在。
要求:时间复杂度小于O(N);
解法一:利用返回值判断释放某一列是否存在相关数值
#include <stdio.h>
int FindNumber(int n, int arr[2][3])
{
int col;
for (col = 3;col >= 0; col--)
{
if (arr[0][col] > n)
continue;
else
return col;
}
//找不到比要查找值更小的数字
return -1;
}
int main()
{
int n;
printf("请输入要查找的数字:");
scanf("%d",&n);
int arr[3][4] = {
{2,4,9,18} ,
{3,8,10,19},
{5,14,12,20}
};
int col= FindNumber(n,arr[3][4],col);
//利用返回值判断释放某一列是否存在相关数值
if (col != -1)
{
for (int row = 0;row < 3;row++)
{
if (arr[row][col] == n)
{
printf("找到了位于:%d行%d列\n", row, col);
}
}
}
printf("找不到\n");
return 0;
}
解法二:直接利用寻找行时是否有符合比其更小值,若有直接进行寻找(更简便)
int main()
{
int n;
printf("请输入要查找的数字: ");
scanf("%d", &n);
int arr[3][4] = {
{2, 4, 9, 18},
{3, 8, 10, 19},
{5, 14, 12, 20}
};
int row = 0;
int col = 3;
while (row < 3 && col >= 0)
{
if (arr[row][col] == n)
{
printf("找到了位于:%d行%d列\n", row, col);
return 0;
}
else if (arr[row][col] > n)
{
col--;
}
else
{
row++;
}
}
printf("找不到\n");
return 0;
}