面试题4:二维数组的查找

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

 

1.bruteforce.cpp(暴力解法)

#include <iostream>
#include <vector>

using namespace std;

class Solution
{
public:
	bool Find(vector<vector<int> > array, int target)
	{
		int row = 0, col = 0, t = 0;
		bool isFound = false;

		for (int i = 0; i < array.size(); i++)
		{
			for(int j = 0; j < array[i].size(); j++)
			{
				if(false == isFound && target == array[i][j])
				{
					isFound = true;
				}
			}
		}
		return isFound;
	}	
};

2.以右上角元素为界开始查找

 

比他小的数必定在它的左侧,就往左找

比他大的数必定在它的下侧,就往下找

#include <cstdio>

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 * colomns + column] > number)
				-- column;
			else
				++ row;
		}
	}
	return found;
}

3.以左下角为界开始查找

比他小的数必定在它的上侧,就往上找

比他大的数必定在它的右侧,就往右找

#include <iostream>

class Solution
{
public:
	bool Find(vector<vector<int> > array, int target)
	{
		bool found = false;
		int row = array.size();
		int col = array[0].size();

		//从左下角的元素开始找起
		//如果查找的元素比当前位置元素小,就向上找
		//如果查找的元素比当前位置元素大,就向右找
		for (int i = row - 1, j = 0; (i >= 0 && i < row) && (j >= 0 && j < col); )
		{
			if (target == array[i][j])
			{
				found = true;
				break;
			} else if (target < array[i][j]) i--;
				else j++;
		}
		return found;
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值