剑指offer1: 组类型——二维数组中的查找(给定一个数字,查找是否在该数组中)

1. 思路:

缩小范围

2. 方法:

(1)要查找的数字等于数组中的数字,结束查找过程;

(2)要查找的数字小于数组中的数字,去除该数字右边的数字,在剩下的数字里查找;

(3)要查找的数字大于数组中的数字,去除该数字上边的数字,在剩下的数字里查找。

3. 图例

4. C++实现 

#include <iostream>
#include <vector>
 
using namespace std;
 
class Solution {
public://类、公有成员、成员函数
    bool Find(int target, vector<vector<int>> array) {//用vector类声明了一个二维数组对象array
        int lrow = array.size();//.表示对象的成员运算符,array.size()表示的是array的行数
        int lcol = array[0].size();//array[0].size()表示的是第一行的列数
        if (!array.empty() && rows>0 && cols>0) {
            int row = 0;
            int col = lcol - 1;
            while (row<lrow && col >= 0) {
                if (array[row][col] == target) {
                    cout << "find!" << endl;
                    return true;
                }
                else if (array[row][col] > target) {
                    --col;
                }
                else {
                    ++row;
                }
            }
        }
        cout << "not find" << endl;
        return false;
    }
};
 
int main()
{
    Solution answer;//声明了一个对象
 
    int array_temp[4][4] = { 1,2,8,9,
        2,4,9,12,
        4,7,10,13,
        6,8,11,15
    };

    int i, j;
    int target=7;
 
    vector<vector<int>> array(4);//声明了一个4行的二维动态数组
     for (i = 0; i < array.size(); i++)
    {
        array[i].resize(4);//重置array的每一行向量的元素个数,即每一行有多少列,这里都是4列
    }
 
    for (i = 0; i < array.size(); i++)
    {
        for (j = 0; j < array[0].size(); j++)
        {
            array[i][j] = array_temp[i][j];
        }
    }
 
    answer.Find(target, array);//这个类对象调用类的成员函数
    getchar();

    return 0;
}
View Code

参考资料

https://blog.csdn.net/happiness_llz/article/details/82530668

原文地址:https://www.cnblogs.com/wxwhnu/p/11390308.html