(本博客旨在个人总结回顾)
题目描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样一个二维数组和一个整数,判断数组中是否含有该整数。
例如下面的二维数组就是每行、每列都递增排序。如果在这个数组中查找数字7,则返回true;如果查找数字5,由于数组不含有该数字,则返回false.
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
解决思路:
从第一行递增,最后一列递减开始查找,若当前的值大于搜索的值,列数减1;若当前值小于搜索值,行数加1;若当前值等于搜索值则返回true。
测试例子:
①搜索值为最大值,最小值,中间某个值。
②搜索值为比最大值大的值,最小值小的值,大于最小值且小于最大值但不存在与二维数组的值。
③传入空指针,行列小于等于0。
/*
* @name Find
* @brief 查找二维数据是否有某个值
* @param [in] int * matrix 二维数组(每一行从左到右递增,每一列从上到下递增)
* @param [in] int nRows 二维数组行数
* @param [in] int nColumns 二维数组列数
* @param [in] int nNumber 查找的目标值
* @return bool
*/
bool Find(int* pMatrix, int nRows, int nColumns, int nValue)
{
bool bFind = false;
if (pMatrix != NULL && nRows > 0 && nColumns > 0)
{
int nRow = 0;
int nColumn = nColumns - 1;
while (nRow < nRows && nColumn >= 0)
{
if (pMatrix[nRow * nColumns + nColumn] == nValue)
{
bFind = true;
break;
}
else if (pMatrix[nRow * nColumns + nColumn] > nValue)
{
nColumn--;
}
else
{
nRow++;
}
}
}
return bFind;
}
完整例子:
// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
/*
* @name Find
* @brief 查找二维数据是否有某个值
* @param [in] int * matrix 二维数组(每一行从左到右递增,每一列从上到下递增)
* @param [in] int nRows 二维数组行数
* @param [in] int nColumns 二维数组列数
* @param [in] int nNumber 查找的目标值
* @return bool
*/
bool Find(int* pMatrix, int nRows, int nColumns, int nValue)
{
bool bFind = false;
if (pMatrix != NULL && nRows > 0 && nColumns > 0)
{
int nRow = 0;
int nColumn = nColumns - 1;
while (nRow < nRows && nColumn >= 0)
{
if (pMatrix[nRow * nColumns + nColumn] == nValue)
{
bFind = true;
break;
}
else if (pMatrix[nRow * nColumns + nColumn] > nValue)
{
nColumn--;
}
else
{
nRow++;
}
}
}
return bFind;
}
int _tmain(int argc, _TCHAR* argv[])
{
int matrix[4][4] = {
{1, 2, 8, 9},
{2, 4, 9, 12},
{4, 7, 10, 13},
{6, 8, 11, 15}
};
//最小值
int nValue = matrix[0][0];
cout << nValue << ":" << (Find((int*)matrix, 4, 4, nValue) ? "true" : "false") << endl;
//最大值
nValue = matrix[3][3];
cout << nValue << ":" << (Find((int*)matrix, 4, 4, nValue) ? "true" : "false") << endl;
//中间值
nValue = matrix[2][2];
cout << nValue << ":" << (Find((int*)matrix, 4, 4, nValue) ? "true" : "false") << endl;
//小于最小值
nValue = matrix[0][0] - 4;
cout << nValue << ":" << (Find((int*)matrix, 4, 4, nValue) ? "true" : "false") << endl;
//大于最大值
nValue = matrix[3][3] + 4;
cout << nValue << ":" << (Find((int*)matrix, 4, 4, nValue) ? "true" : "false") << endl;
//不存在的中间值
nValue = 5;
cout << nValue << ":" << (Find((int*)matrix, 4, 4, nValue) ? "true" : "false") << endl;
//传入一异常
nValue = matrix[0][0];
cout << nValue << ":" << (Find(NULL, 4, 4, nValue) ? "true" : "false") << endl;
cout << nValue << ":" << (Find((int*)matrix, -4, 4, nValue) ? "true" : "false") << endl;
cout << nValue << ":" << (Find((int*)matrix, 4, -4, nValue) ? "true" : "false") << endl;
system("pause");
return 0;
}
运行结果: