zoukankan      html  css  js  c++  java
  • 《剑指offer》 二维数组中的查找

    本题目是《剑指offer》中的题目 二维数组中的查找

    题目:

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

    思路:

      step1:首先取数组中右上角的数字

      step2:判断如果等于目标值,则查找过程结束

      step3:如果该数字大于目标值,剔除这个数字所在的列

      step4:如果该数字小于目标值,剔除这个数在所在的行

    C++ code

    class Solution {
    public:
        bool Find(int target, vector<vector<int> > array) {
            bool result = false;                        //返回结果值,默认为false,后期找到会更改此值
            if (!array.empty()){                        //审核数组是否为空,不为空进入,若为空,直接返回false
                int rows = array.size();                //提取二维数组的行数
                int row = 0;                            //定义行迭代变量,从0开始迭代
                int col = array[0].size()-1;            //定义列迭代变量,从末尾开始迭代
                while (row < rows && col >= 0){         //循环结束条件为行或者列超标
                    if (array[row][col] == target){     //判断相等,更改返回值,并跳出循环
                        result = true;
                        break;
                    }else if (array[row][col] > target){//如果大于目标值则去掉行
                        col -= 1;
                    }else{                              //如果小于目标值则去掉列
                        row += 1;
                    }
                }
            }
            return result;
        }
    };

    Python Code

    # -*- coding:utf-8 -*-
    class Solution:
        # array 二维列表
        def Find(self, target, array):
            # write code here
            result = False                        #该值后期当找到其值时候会被改变
            if array:                             #审核边界条件
                rows = len(array)                 #全部的行
                row = 0                           #迭代的行数
                col = len(array[0])-1             #迭代的列数,遍历时候要减一开始
                while row < rows and col >= 0:    #条件是行列符合规则
                    if array[row][col] == target: #当找到该值时候
                        result = True             #修改返回值,并且推出循环
                        break
                    elif array[row][col] > target:#当大于该值,去掉这一列
                        col -= 1
                    else:                         #当小于该值时候,去掉这一行
                        row += 1
            return result 

    总结:

      二维数组的遍历,自习查看该题目的特点,是有顺序的,所以要查找规律。仔细查看循环的遍历条件。

  • 相关阅读:
    linux 常见知识2
    python 数组
    linux 常见知识
    python入门1
    linux 入门的常见命令
    聊天机器人開發好消息!!DIALOGFLOW與微信的天作之合!!
    群发短信软件共冶一爐
    Ultimate Facebook Messenger for Business Guide (Feb 2019)
    Top 5 Business Messaging Announcements at Facebook F8 2019
    Ultimate Guide to WhatsApp for Business 2019
  • 原文地址:https://www.cnblogs.com/missidiot/p/10749682.html
Copyright © 2011-2022 走看看