其实遍历数组依次比较也可以,这里我们讨论有序二维数组查找。
问题:我们知道数组是从左至右,从上到下递增。输入数字,判断数组里面是否含有该整数。
具体怎么判断分析不再赘述,(《剑指offer》P45)
总结如下规律:1.选取右上角的数字(左下角也可以)。
2.如果要查找的数字等于该数字,结束查找;如果该数字大于要查找的数字。则剔除这个数字所在的列;
如果该数字小于要查找的数字,则提出这个数所在的行。(如果不在数组的右上角,则每一次都在数组的查找范围内剔
除一行或者一列,一步步缩小范围,直到结束)
代码如下:
#include<iostream>
using namespace std;
#define R 4
#define C 5
#define TRUE 1
#define FALSE 0
int Check(int arr[R][C],int n)
{
int i = 0;
int j = 0;
if (n < arr[i][j] || n > arr[R-1][C-1])
{
cout << "n is illegal" << endl;
return -1;
}
int row = 0;
int col = C - 1;
while (col > 0 && row < R)
{
if (n == arr[row][col])
{
cout << "row : " << row << endl;
cout << "col : " << col << endl;
return 1;
}
if (n > arr[row][col])
{
row++;
}
else
{
col--;
}
}
cout << "not found" << endl;
}
int main()
{
int arr[4][5] = { {1,2,3,4,5},{3,4,5,8,9},{5,7,8,12,15},{7,9,10,16,20} };
//输出二维数组
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
{
cout << " " <<arr[i][j];
}
cout << endl;
}
cout << endl;
Check(arr, 8);//查找数字
cout << endl;
Check(arr, 14);//不存在的数
cout << endl;
Check(arr, 0);//越界的数
cout << endl;
Check(arr, 21);//越界的数
cout << endl;
}
运行结果: