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