C++二维数组中的查找算法示例

2025-05-27 0 24

本文实例讲述了C++二维数组中的查找算法。分享给大家供大家参考,具体如下:

一、问题:

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

二、实现代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35
#include <iostream>

#include <vector>

using namespace std;

bool Find(int target, vector<vector<int> > array) {

int row = array.size(); //行数

int column = array[0].size(); //列数

int i = 0, j = column - 1;

while (i < row && j >= 0)

{

if (array[i][j] == target) //从右上角第一个找起,大于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");

}

希望本文所述对大家C++程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++二维数组中的查找算法示例 https://www.kuaiidc.com/74278.html

相关文章

发表评论
暂无评论