01-数组的查找

 1 //二维数组的行和列
 2 // ---若用一维数组存放二维数组时,则前提必须已知行rowCount和列colCount;
 3 // ---若用vector> array保存二维数组时,行数为rowCount = array.size(), 列数为colCount = array[0].size();
 4 
 5 
 6 //题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
 7 //思路: 从右上角开始入手进行查找数字。如果等于该数字,查找结束;若该数字大于要查找的数字,提出这个数字的所在的列;若数字小于要查找的数字,则剔除这个数字所在的行
 8 
 9 
10 // ---若用一维数组存放二维数组时,则前提必须已知行rowCount和列colCount;
11 #include <iostream>
12 #include <vector>
13 using namespace std;
14 class Solution
15 {
16 public:
17     bool Find(int target, vector<vector<int>> array)
18     {
19         //鲁棒性
20         int len = array.size();
21         if (len <= 0)
22         {
23             return false;
24         }
25         int colCount = array[0].size();
26         int rowCount = array.size();
27         //循环条件变量
28         int i, j;
29         for (i = 0, j = rowCount-1; i < rowCount && j>=0;)
30         {
31             if (array[i][j] == target)
32             {
33                 return true;
34             }
35             if (array[i][j] < target)
36             {
37                 i++;
38             }
39             if (array[i][j] > target)
40             {
41                 j--;
42             }
43         }
44         return false;
45     }
46 };
47 int main()
48 {
49     Solution s;
50     bool result;
51     vector<vector<int>> array = { {1,2,3}, {4,5,6}, {7,8,9} };
52     result = s.Find(5, array);
53     if (result)
54     {
55         cout << "Target has already existed" << endl;
56     }
57     else
58     {
59         cout << "Target has not already existed" << endl;
60     }
61     system("pause");
62     return 0;
63 }

 

转载于:https://www.cnblogs.com/maleyang/articles/7379982.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值