• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
煎蛋啊
博客园    首页    新随笔    联系   管理    订阅  订阅
二维数组中的查找

题目描述:

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

基本思想:首先选取数组右上角的数字。如果该数字等于要查找的数字,查找过程结束;

         如果该数字大于要查找的数字,剔除这个数字所的列。

     如果该数字小于要查找的数字,剔除这个数字所在的行。

#include <iostream>
#include <algorithm>
#include "string.h"
#include "stdio.h"
#include <vector>
#include <deque>
#include <stack>
#include<map>
#include<utility>
#include "math.h"
using namespace std;
class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        if(array.size() == 0)
            return false;
        int i=0;
        int j=array[0].size()-1;
        while(i<array.size()&&j>=0)
        {
               if(array[i][j]==target)
                return true;
            else if(array[i][j]<target)
               {
                i++;
            }
            else
            {
                j--;
            }
        }
        return false;
    }
};
int num;
int target;
int main() {
    cin >> num;
    cin >>target;
    vector<int> arr(num);
    vector<vector<int> > array(num);

    for(int i=0;i<num;i++)
    {
        for(int j=0;j<num;j++)
        {
            cin>>arr[j];
        }
        array[i]=arr;
    }
    for(int i=0;i<array.size();i++)
    {
        for(int j=0;j<array[0].size();j++)
        {
            cout<<array[i][j]<<" ";
        }
        cout<<endl;
    }
    Solution solution;
    bool result = solution.Find(target,array);
    cout<<"RESUL:"<<result<<endl;
    return 0;
}

 

posted on 2017-03-30 10:19  煎蛋啊  阅读(226)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3