exercise13

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

1 3 4
2 4 5
4 5 6

#include<stdio.h>
#pragma warning(disable:4996)

#define ROW 3
#define COL 3

int search(int arr[][COL], int k, int row, int col)
{
	int x = 0;
	int y = col - 1;
	while ( x<row && y >= 0)//key与右上角的数比较,行减1,列减一,直到找到左下角的数
	{
		if (k > arr[x][y])
		{
			x++;
		}
		else if (k == arr[x][y])
		{
			return 1;
		}
		else
		{
			y--;
		}
	}
	return 0;
}

int main()
{
	int arr[ROW][COL] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int key;
	printf("PLease input a number:\n");
	scanf("%d",&key);
	int ret = search(arr, key, ROW, COL);
	if (1 == ret)
	{
		printf("找到了\n");
	}
	else
	{
		printf("找不到\n");
	}

	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/zn_wuxunian/article/details/80197677