**杨氏矩阵 有一个二维数组. 数组的每行从左到右是递增的,每列从上到下是递增的. 在这样的数组中查找一个数字是否存在。 时间复杂度小于O(N);** 数组:

杨氏矩阵
有一个二维数组.
数组的每行从左到右是递增的,每列从上到下是递增的.
在这样的数组中查找一个数字是否存在。
时间复杂度小于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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章