题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
例如:下列二维数组每行、每列递增,查找7返回true,查找5返回false
1 | 2 | 8 | 9 |
2 | 4 | 9 | 12 |
4 | 7 | 10 | 13 |
6 | 8 | 11 | 15 |
分析一波:选取二维数组的某个角开始查找会不会简单?可以先以7为例带入进行查找,试图寻找规律。
设要查找的数为n
一行中最大的数在行末尾,一列中最大的数在行末尾,如果n大于行末尾,则说明n大于该行所有的数,说明n不在该行。
1.从右上角开始(第一行末尾),9>7,说明7在9的左边
1 | 2 | 8 | 9 |
2 | 4 | 9 | 12 |
4 | 7 | 10 | 13 |
6 | 8 | 11 | 15 |
2.右上角 8 > 7说明还在左边
1 | 2 | 8 | 9 |
2 | 4 | 9 | 12 |
4 | 7 | 10 | 13 |
6 | 8 | 11 | 15 |
3.右上角 2 < 7,在下边
1 | 2 | 8 | 9 |
2 | 4 | 9 | 12 |
4 | 7 | 10 | 13 |
6 | 8 | 11 | 15 |
以此类推,马上找到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.本题也可以从左下角找起,复杂度一致。