题目:一个二维数组,数组的每行从左到右是递增的,每列从上到下是递增的,在这样的数组中找一个数是否存在。时间复杂度小于O(n)。

分析:在二维数组中找一个数,应该遍历整个数组找这个数,但是题目中的二维数组每行从左到右是递增的,每列从上到下是递增的,这样给搜索带来了便利。先判断这个数是否小于arr[0][0]这个数,或大于arr[row][col](数组中的最大值)这个数,如果满足其一就直接说明搜索不到这个数。当不满足这个条件后就可以进入循环,先用这个数与第一行最后一列的数字比较,如果大于就进入下一列比较最后一个,知道小于最后一个数,如果小于了,就可以确定这个数就在这一行。向前遍历,如果有就找到了,如果没有就返回找不到。

Find_num函数

int Find_num(const int arr[][5], int row, int f)
{
	
	assert(arr != NULL);
	if ((f < arr[0][0]) || (f > arr[row - 1][4]))
		return 0;
	int line = 0;
	int col = 4;
	while ((line < row) && (col >= 0))
	{
		if (f > arr[line][col])
		{
			line++;
		}
		else if (f < arr[line][col])
		{
			col--;
		}
		else
		{
			return f;
		}
	}
	return 0;
}

代码如下

#include <stdio.h>
#include <assert.h>

int Find_num(const int arr[][5], int row, int f)
{
	
	assert(arr != NULL);
	if ((f < arr[0][0]) || (f > arr[row - 1][4]))
		return 0;
	int line = 0;
	int col = 4;
	while ((line < row) && (col >= 0))
	{
		if (f > arr[line][col])
		{
			line++;
		}
		else if (f < arr[line][col])
		{
			col--;
		}
		else
		{
			return f;
		}
	}
	return 0;
}
int main()
{
	int ret[][5] =
	{
		{ 1, 2, 3, 4, 5 },
		{ 6, 7, 8, 9, 10 },
		{ 11, 12, 13, 14, 15 },
		{ 16, 17, 18, 19, 20 }
	};
	int find_num = 0;

	printf("输入需要查找的数-> ");
	scanf("%d",&find_num);
	if (Find_num(ret, 4, find_num))
		printf("find the number\n");
	else
		printf("not find\n");
}

运行结果
杨氏矩阵

相关文章: