《剑指offfer》面试题4:二维数组中的查找

题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

分析:三种情况查找,数组中任选一数字,与目标数字比较,相等,小于,大于

输入数组:   1   2    8    9
                     2   4    9   12
                     4   7   10  13
                     6   8   11  15

总结:

首先选取数组中右上角的数字。

该数字 = key,查找结束;

该数字 > key,剔除该数字所在列;

该数字 < key,剔除该数字所在行。

即,如果要查找的数字不在数组的右上角,则每一次都在数组的查找范围中剔除一行或者一列。

#include<cstdio>
#include<iostream>

using namespace std;

bool Find(int* matrix, int rows, int columns, int number)
{
	bool found = false;

	if (matrix != nullptr && rows > 0 && columns > 0)
	{
		int row = 0;
		int column = columns - 1;
		while (row < rows && column >= 0)                   
		{
			if (matrix[row * columns + column] == number)  //matrix[row, column] 该数字的位置
			{                                             //matrix[row * columns + column] 行*列+余
				found = true;
				break;
			}
			else if (matrix[row * columns + column] > number)
				--column;
			else
				++row;
		}
	}
	return found;
}

int main()
{
	//数组
	int matrixs[][4] = { { 1, 2, 8, 9 },
			     { 2, 4, 9, 12 }, 
			     { 4, 7, 10, 13 }, 
			     { 6, 8, 11, 15 } };
	bool result1 = Find(*matrixs, 4, 4, 7);
	bool result2 = Find(*matrixs, 4, 4, 5);
	bool result3 = Find(*matrixs, 4, 4, 1);
	cout << result1 << endl;
	cout << result2 << endl;
	cout << result3 << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38734403/article/details/81417372