题目:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
知识点:
- 创建二维数组(居然忘了!)
注意:
- 写代码之前,先将输入的范围固定
代码实现(java):
- 先将要查找数字num与数组右上的数字进行比较,大于则删除列,小于则删除行,等于输出true
/**
* 先将要查找数字num与数组右上的数字进行比较,大于则删除列,小于则删除行,等于输出true
* @param arrs
* @param num
* @return
*/
private static boolean findNum(int[][] arrs, int num) {
if(arrs!=null) {
//判断右上方的数是否与查找数相等
int rowNums = arrs[0].length;
int columnIndex = arrs.length-1;
int rowIndex = 0;
while(rowIndex<=rowNums-1 && columnIndex>=0) {
if(num == arrs[rowIndex][columnIndex]) {
return true;
}else if(num < arrs[rowIndex][columnIndex]) {
columnIndex--;
}else {
rowIndex++;
}
}
//若大于,则删除整列,继续判断;
//若小于,则删除整行,继续判断;直至等于查找的数
return false;
}else {
return false;
}
}
代码实现(c++):
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
bool Find(vector<vector<int> > array, int target)
{
bool found = false;
int row = 0;
int col = array[0].size() - 1;
//循环至row大于array[0].size()-1或col小于0
while (row <= array[0].size()-1 && col >= 0)
{
//比较target与右上角数的大小
if (array[row][col] == target)
{
found = true;
break;
}
else if (array[row][col] < target)
{
row++;
}
else
{
col--;
}
}
return found;
}
int main()
{
vector< vector<int> > vec(2, vector<int>(4));
//赋值
int a[2][4] = { { 1, 2, 8, 9 },{ 4, 7, 10, 13 } };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
vec[i][j] = a[i][j];
}
}
//打印
int m, n;
for (m = 0; m < vec.size(); m++)
{
for (n = 0; n < vec[0].size(); n++)
{
cout << vec[m][n] << " ";
}
cout << endl;
}
bool isTrue = false;
cout << isTrue << endl;
isTrue = Find(vec, 7);
cout << isTrue << endl;
getchar();
return 0;
}