楊氏矩陣
有一個二維數組.
數組的每行從左到右是遞增的,每列從上到下是遞增的.
在這樣的數組中查找一個數字是否存在。
時間複雜度小於O(N);
數組:
1 2 3
2 3 4
3 4 5
1 3 4
2 4 5
4 5 6
解析:
假如把數組的右上角作爲選定數,如下圖a。即3爲選定數字,假設查找數字爲7,第一次比較,7>3,因爲3是第0行最大的數字,則7不可能出現在3所在行,所以將3所在行數剔除,得到圖b,那麼此時選定數字變爲6,因爲6<7,所以剔除6所在行,得到圖c。則7一定在此時9所在行中。
代碼如下:
#include<stdio.h>
#include<stdlib.h>
int Find_number(int arr[3][3], int *px, int *py, int key)
{
int x=0;
int y = *py - 1;
while ((x <= (*py - 1)) && (y >= 0))
{
if(arr[x][y] == key)
return 1;
else if (arr[x][y] < key)
x++;
else
y--;
}
return 0;
}
int main()
{
int arr[][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int num = 0;
int x = 3;//行數爲3
int y = 3;//列數爲3
int result = 0;
scanf("%d", &num);
result = Find_number(arr, &x, &y, num);//x和y傳相應的地址
if (result)
{
printf("find it,the location is %d %d\n", x, y);
}
else
printf("can't find it\n");
system("pause");
return 0;
}