剑指offer面试题4: 二维数组中的查找

题目描述

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
#include <iostream>
#include <vector>

using namespace std;

class Solution {
 public:
     bool Find(int target, vector<vector<int> > array)
     {   
        unsigned rows = array.size();
        unsigned cols = array[0].size();
        if (array.size() > 0 && rows > 0 && cols > 0)
        {   
            int row = 0;
            int col = cols - 1;
            while(row < rows && col >= 0)
            {   
                if (array[row][col] == target) {
                   return true; 
                }   
                else if (array[row][col] > target) {
                    --col;
                }   
                else {
                    row++;
                }   
            }   
        }   
        return false;
     }   
};

int main()
{
    vector<vector<int> > v;
    v.push_back({1,2,8,9});
    v.push_back({2,4,9,12});
    v.push_back({4,7,10,13});
    v.push_back({6,8,11,15});

    Solution s;
    if (s.Find(0, v))
    {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }


    if (s.Find(9, v))
    {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/douzujun/p/10646467.html