有一个杨氏矩阵,每行从左往右是递增的,从上到下是递增的,请编写程序,在这样的矩阵中查找某个数字是否存在。
要求:时间复杂度小于O(N)
(要是没有这个要求我们可以遍历二维数组来实现)
依次判断右上角的数是不是这个数,>排除一列,<排除一行
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
//杨氏矩阵
int search(int arr[3][3], int n, int row, int col)
{
int x = 0;
int y = col - 1;
while (x <= row - 1 && y >= 0)
{
if (arr[x][y] > n)
{
y--;
}
else if (arr[x][y] < n)
{
x++;
}
else
{
return 1;
}
}
return 0;
}
int main()
{
int arr[3][3] = { 1,2,4,3,4,6,5,8,9 };
int n = 0;
scanf("%d", &n);
int ret = search(arr, n, 3, 3);
printf("%d", ret);
return 0;
}
若想知道这个数是在什么位置可以通过结构体带回,或者通过指针带回
1.指针
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int search(int arr[3][3], int n, int *r, int *c)
{
int x = 0;
int y = *c- 1;
while (x <= *r - 1 && y >= 0)
{
if (arr[x][y] > n)
{
y--;
}
else if (arr[x][y] < n)
{
x++;
}
else
{
*r = x;//找到函数的时候把xy的值带回来
*c = y;
return 1;
}
}
*r = -1;//没找到返回-1,-1
*c = -1;
return 0;
}
int main()
{
int arr[3][3] = { 1,2,4,3,4,6,5,8,9 };
int n = 0;
scanf("%d", &n);
int x = 3;
int y = 3;
int ret = search(arr, n, &x, &y);
printf("%d %d\n", x, y);
printf("%d\n", ret);
return 0;
}
2,结构体(定义一个返回值类型为结构体的函数,结构体可以带回来多个数)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
struct Point
{
int x;
int y;
} ;
struct Point search(int arr[3][3], int n, int row, int col)
{
int x = 0;
int y = col - 1;
struct Point p = { -1,-1 };
while (x <= row - 1 && y >= 0)
{
if (arr[x][y] > n)
{
y--;
}
else if (arr[x][y] < n)
{
x++;
}
else
{
p.x = x;//赋值
p.y = y;
return p;//找到返回坐标
}
}
return p;//找不到返回-1,-1
}
int main()
{
int arr[3][3] = { 1,2,4,3,4,6,5,8,9 };
int n = 0;
scanf("%d", &n);
struct Point ret = search(arr, n, 3,3);
printf("%d %d\n", ret.x, ret.y);
return 0;
}