目录
解题分析:
- 杨氏矩阵
- 有一个二维数组.
- 数组的每行从左到右是递增的,
- 每列从上到下是递增的.
- 在这样的数组中查找一个数字是否存在。
- 时间复杂度小于O(N);
- 数组:
1 2 3
2 3 4
3 4 5
1 3 4
2 4 5
4 5 6
1 2 3
4 5 6
7 8 9
- 首先对于一个二维数组,寻找一个数是否存在,进行一遍遍历即可;
- 鉴于这个数组中的数从左到右递增,从上到下递增,所以先从对角线右上角元素寻找;
代码示例:
#include<stdio.h>
#include<stdlib.h>
int Findnum(int arr[][4], int row, int key) {
int i = 0;
int j = 3;
while (i < row && j >= 0) {
if (arr[i][j] > key) {
j--;
}
else if (arr[i][j] < key) {
i++;
}
else {
return 0;
}
}
return -1;
}
int main() {
int key = 0;
int row = 0;
int col = 0;
int arr[4][4] = { 1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16 };
for (row= 0; row< 4; ++row) {
for (col = 0; col< 4; ++col) {
printf("%4d", arr[row][col]);
}
printf("\n");
}
printf("请输入你要查找的数:");
scanf_s("%d", &key);
int ret=Findnum(arr, 4, key);
if (ret == 0) {
printf("矩阵里存在%d\n", key);
}
else {
printf("矩阵里不存在%d\n", key);
}
system("pause");
return 0;
}
运行结果:
运行结果: