- 首先先了解一下杨氏矩阵 杨氏矩阵是一个从左到右依次递增,从上到下依次递增的二维数组
比如:1 2 3
2 3 4
3 4 5
解法思路:
- 如果要在杨氏矩阵中查找一个数,且时间复杂度小于O(N),那根据该数组特点依次递增的特性,则可以先从数组的每一行的最一个元素开始,如果相等就直接输出,如果小于要查找的数则用下一行的最后一个元素再去比较。如果大于就用该行后面的数取依次比较即可。
程序如下:
#include<stdio.h>
bool Reseach_sou(int arr[][3], int row,int col, int key)
{
int i = 0;
int j = col-1;
//从第一行,最后一列开始寻找
while ((j >= 0) && (i <= 2))
{
if (arr[i][j] == key)
return true;
else if (arr[i][j] < key)
i++;
else
j--;
}
return false;
}
int main()
{
int arr[][3] = {1, 2 ,3, 2, 3, 4, 3, 4, 5};
int key = 0;
int row = 3;
int col = 3;
scanf("%d",&key);
Reseach_sou(arr, row, col, key);
//如果找到返回true,找不到返回false
if(Reseach_sou(arr, row, col, key))
return printf("找到了!\n");
else
printf("没找到!\n");
return 0;
}
改进:返回被查找的元素在数组中的位置
方法一:使用结构体变量
#include<stdio.h>
#include<string.h>
struct Point //定义一个结构体
{
int i;
int j;
};
struct Point Reseach_sou(int arr[][3], int row, int col, int key)
{
int i = 0;
int j = col-1;
struct Point ret = {-1,-1};
while ((j >= 0) && (i <= 2))
{
if (arr[i][j] == key)
{
ret.i = i;
ret.j = j;
return ret;
}
else if (arr[i][j] < key)
i++;
else
j--;
}
return ret;
}
int main()
{
int arr[][3] = {1, 2 ,3, 2, 3, 4, 3, 4, 5};
int row = 3;
int col = 3;
struct Point ret = Reseach_sou(arr, row, col, 5);
//返回一个结构体变量
if ((ret.i != -1)&&(ret.j != -1))
printf("找到了,坐标为:%d %d\n",ret.i, ret.j);
else
printf("找不到\n");
return 0;
}
方法二:返回型参数
#include<stdio.h>
//pi,pj为i,j的地址,*解引用为i,j的值
int Reseach_sou(int arr[][3], int *pi, int *pj, int key)
{
int i = 0;
int j = *pj-1;
while ((j >= 0) && (i <= *pi))
{
if (arr[i][j] == key)
{
*pi = i;
*pj = j;
return;
}
else if (arr[i][j] < key)
i++;
else
j--;
}
*pi = -1;
*pj = -1;
}
int main()
{
int arr[][3] = {1, 2 ,3, 2, 3, 4, 3, 4, 5};
int i = 3;
int j = 3;
int key = 0;
scanf("%d",&key);
Reseach_sou(arr, &i, &j, key);//取x,y的地址
if ((i != -1)&&(j != -1))
printf("找到了,下标为:%d %d\n",i, j);
else
printf("找不到\n");
return 0;
}