题目:二维数组每行从左到右递增,每列从上到下递增;输入一个这样的二维数组和一个整数,判断数组中是否包含该整数。
代码示例:
#include<iostream>
using namespace std;
const int row = 4;
const int col = 5;
/*
**二维数组从左到右,从上到下递增,查找num是否在该数组中。
**从右上角开始查找
*/
bool FindNum(int a[][5], int num,int m, int n)
{
if (m <= 0 || n <= 0)
return false;
int i = 0; int j = n - 1;
while ((0 <= i&&i <= m - 1) && (0 <= j&&j <= n - 1))
{
if (a[i][j] == num)
return true;
else if (a[i][j] < num)
{
i = i + 1;
}
else
{
j = j - 1;
}
}
return false;
}
void main()
{
int a[row][col] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 } };
int num = -1;
bool flag = FindNum(a, num, row, col);
if (flag)
{
cout << num << "在该数组中!" << endl;
}
else
cout << num << "不在该数组中!" << endl;
}