I, entitled
There is a two-dimensional array, each row of the array is incremented from left to right, top to bottom of each column is incremented to find whether there is a number in this array.
Requirements: less than the time complexity of O (N);
Second, the idea
. 4. 6. 1
2. 5. 7
. 3. 6. 9
idea: to find a number of conventional two-dimensional array in such methods are traversed from beginning to end once all of the figures, in this case time complexity is O (n), does not meet the topics requirements;
make complexity less than O (n), meaning that they can not traverse from start to finish, we can re-select a starting point. (Such a time to start looking two-dimensional array of five choices,
middle, upper-left corner, upper right corner, bottom left, bottom right corner, but obvious, from the middle or upper-left corner, lower right corner to start, then, larger or smaller than his direction more, traverse a lot of trouble.
and the top right and bottom left more convenient, a direction is bigger than him, a direction is smaller than him. this time, we chose the top right corner as the starting position.
Third, code implementation
#include<stdio.h>
#include<Windows.h>
#pragma warning(disable:4996)
int YangSquare(int a[][3], int x, int y,int z)
{
int i = 0; int j = 2;
while (i<x&&j>=0)
{
if (z > a[i][j])
{
i++;
}
else if (z < a[i][j])
{
j--;
}
else
{
return z;
}
}
return 0;
}
int main()
{
int z = 0;
int a[3][3] = { 1, 4, 6,
2, 5, 7,
3, 6, 9 };
printf("请输入你要查找的数:\n");
scanf("%d", &z);
printf("%d\n",YangSquare(a, 3, 3,z));
system("pause");
return 0;
}