剑指offer 面试题4 二维数组中的查找

问题:在一个特殊的二维数组(右边的数比左边的数大,下面的数比上面的数大)中查找是否存在某个数字。

输入:二维数组,行,列,某个数字

输出:某个数字是否存在

思路:重述下书上提供的思路,从数组的右上角(或者左下角)开始比对。

如果某个数字小于数组中选择的数,则删除该列,向左移动进行比对。

如果某个数字大于数组中选择的数,则删除该行,向下移动进行比对。

如果某个数字等于数组中选择的数,则存在,否则不存在。

代码:

#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)
			{
				found = true;
				break;
			}
			else if(matrix[row*columns+column]<number)
			{
				row++;
			}
			else
			{
				column--;
			}
		}
	}
	return found;
}
int main()
{
	int matrix[] = {1, 2, 8, 9, 2, 4, 9, 12, 4, 7, 10, 13, 6, 8, 11, 15};
	if(Find(matrix, 4, 4, 5))
		cout<<"true"<<endl;
	else
		cout<<"false"<<endl;
	return 0;
}

复杂度分析:时间复杂度为O(rows+columns),空间复杂度为O(1)。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值