(本博客旨在個人總結回顧)
題目描述:
在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣一個二維數組和一個整數,判斷數組中是否含有該整數。
例如下面的二維數組就是每行、每列都遞增排序。如果在這個數組中查找數字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;
}
運行結果: