本文實(shí)例講述了C++二維數(shù)組中的查找算法。分享給大家供大家參考,具體如下:
一、問(wèn)題:
在一個(gè)二維數(shù)組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請(qǐng)完成一個(gè)函數(shù),輸入這樣的一個(gè)二維數(shù)組和一個(gè)整數(shù),判斷數(shù)組中是否含有該整數(shù)。
二、實(shí)現(xiàn)代碼:
#include <iostream>#include <vector>using namespace std;bool Find(int target, vector<vector<int> > array) { int row = array.size(); //行數(shù) int column = array[0].size(); //列數(shù) int i = 0, j = column - 1; while (i < row && j >= 0) { if (array[i][j] == target) //從右上角第一個(gè)找起,大于target向左查找,小于target則向下查找 { return true; } else if (array[i][j] > target) { j--; //向左查找 } else { i++; //向下查找 } } return false;}int main(){ vector<int> vec1{ 3, 7, 9, 12, 19, 23 }; vector<int> vec2{ 4, 17, 19, 31, 32, 33 }; vector<vector<int> > array; array.push_back(vec1); array.push_back(vec2); bool result = Find(32, array); cout << "result = " << result << endl; system("pause");}希望本文所述對(duì)大家C++程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注