二维数组的查找

本文介绍了一种在二维有序数组中高效查找特定数值的方法。数组的每一行从左到右递增排序,每一列从上到下递增排序。通过选择右上角或左下角的元素作为起点,与目标值进行比较,逐步缩小搜索范围,直至找到目标值或确定不存在。

剑指offer:二维数组,行按照从左到右递增的顺序排序,列按照从上到下的顺序进行排序

思路:选取右上角或者左下角的数字和要查找的数字作比较,建议画图示意,思路非常清晰

#include<iostream>
using namespace std;
bool Find(int *matrix, int rows, int cols, int number)
{
	bool found = false;
	if (matrix != NULL &&rows > 0 && cols > 0)
	{
		int row = 0;
		int col = cols - 1;
		while (row < rows && cols >= 0)
		{
			if (matrix[row*cols + col] == number)
			{
				found = true;
				break;
			}
			else if (matrix[row*cols + col]>number)
				--col;
			else
				++row;
		}
	}
	return found;
}
int main()
{
	bool flag = false;
	int row=0,col=0,num=0;
	int test[3][3];
	cout << "输入如下:" << endl;
	cin >> row >> col >> num;
		for (int i = 0; i < row; i++)
		{
			for (int j = 0; j < col; j++)
			{
			cin >> test[i][j];
			}
		}
	flag = Find(*test, row, col, num);
	if (flag == false)
		cout << "false" << endl;
	else
		cout << "true" << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值