剑指offer--(2.3.2)面试题3:二维数组中的查找
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。例如这个数组中,查找7,返回true;查找5,返回flase。
解决方法:从右上角开始,如果该数字等于要查找的数字,查找过程结束,结果该数字大于要查找的数字,剔除这个数字所在的列,如果该数字小于要查找的数字,剔除这个数字所在的行。每一步都可以缩小范围,直到找到要查找的数字,或者查找范围为空。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
//二维数组中的查找,matrix是带查找的数组,number是要查找的数,return true代表找到了,return false代表没找到
bool Find(int *matrix, int rows,int columns, int number)
{
bool found = false;
//数组满足条件可进入
if(matrix != NULL && rows > 0 && columns > 0)
{
int row = 0; //起始开始的行号
int column = columns - 1;//起始开始的列号
//要查找的位置确保在数组之内,行小于数组总行,列大于等于0列,因为从右上角往左下角走
while(row < rows && column >= 0)
{
//先从右上角开始找
if(matrix[row * columns + column] == number)
{
found = true;
break;
}
else if(matrix[row * columns + column] > number)//如果大于查找的数字就剔去一列
-- column;
else //如果小于,就剔去一行
++ row;
}
}
return found;
}
int main()
{
int a[][4]={
{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
cout<<boolalpha<<Find(*a,4,4,7)<<endl;
printf("%d",Find(*a,4,4,7));
}
输出结果为: