剑指Offer_面试题03_二维数组中的查找

63 篇文章 1 订阅
40 篇文章 0 订阅

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


例如:下列二维数组每行、每列递增,查找7返回true,查找5返回false

1  2  89
24912
471013
681115

分析一波:选取二维数组的某个角开始查找会不会简单?可以先以7为例带入进行查找,试图寻找规律。

设要查找的数为n

一行中最大的数在行末尾,一列中最大的数在行末尾,如果n大于行末尾,则说明n大于该行所有的数,说明n不在该行。

1.从右上角开始(第一行末尾),9>7,说明7在9的左边

1  2  89
24912
471013
681115

2.右上角 8 > 7说明还在左边

1  2  89
24912
471013
681115


3.右上角 2 < 7,在下边

1  2  89
24912
471013
681115


以此类推,马上找到7

#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
//C风格
bool Find(int* matrix, int rows, int columns, int number)
{
	bool found = false;
	if (matrix != NULL && rows > 0 && columns > 0)
	{
		//获取右上角坐标
		int row = 0;
		int col = columns - 1;
		while (row < columns && col >= 0)
		{
			if (matrix[row * rows + col] == number)
			{
				found = true;
				break;
			}
			else if (matrix[row * rows + col] > number)
				--col;
			else
				++row;
		}
	}
	return found;
}
//C++风格
bool Find(vector<vector<int> >array, int target)
{
	if (array.empty())
		return false;
	bool found = false;
	int rows = array.size();
	int cols = array[0].size();

	int x = 0;
	int y = cols - 1;
	while (x >= 0 && y >= 0)
	{
		if (array[x][y] == target)
		{
			found = true;
			break;
		}
		else if (array[x][y] > target)
			--y;
		else
			++x;
	}

	return found;
}
//验证
int main()
{
	int matrix[] = { 1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15 };
	vector<vector<int> > matrix2 = { {1,2,8,9},
	{2,4,9,12}, {4,7,10,13}, {6,8,11,15} };

	cout << Find(matrix, 4, 4, 7) << endl;
	cout << Find(matrix2, 7) << endl;
	system("pause");
	return 0;
}

总结:1.复杂问题可以通过例子找出规律

           2.本题也可以从左下角找起,复杂度一致。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值