题目:杨氏矩阵
有一个二维数组.
数组的每行从左到右是递增的,每列从上到下是递增的.
在这样的数组中查找一个数字是否存在。
时间复杂度小于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
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int findNum(int a[][3], int x, int y, int f){
int i=0,j=y-1;
while (j >= 0&& i < x){ //边界条件:列数不能小于0,行数不能大于x
if (a[i][j] < f){ //如果要找的数大于目前所在位置的数则行数+1
i++;
}
else if (a[i][j]>f){ //如皋要找的数小于目前所在位置的数则列数-1
j--;
}
else{
return 1;
}
}
return 0;
}
int main(){
int a[3][3] = { { 1, 3, 5 },
{ 3, 5, 7 },
{ 5, 7, 9 }, };
if (findNum(a, 3, 3, 6)){
printf("It has been find!\n");
}
else {
printf("It hasn't been find!\n");
}
system("pause");
return 0;
}