zoukankan      html  css  js  c++  java
  • 二维数组的查找

    题目描述

    在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
    注意:含有的意思是在两个数的区间之内,而不是非得要有这样一个数等于他
    思路:从左下角开始找
    python:
     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     def Find(self, target, array):
     4         # write code here
     5         row = len(array) - 1
     6         col = len(array[0]) - 1
     7         r = row
     8         c = 0
     9         while r >= 0 and c<= col:
    10             if target < array[r][c]:
    11                 r -= 1
    12             elif target > array[r][c]:
    13                 c += 1
    14             else:
    15                 return True
    16         return False
    思路:

    从array的最后一行的第一个元素开始比较。

    大于这个元素的话,就只需这一行进行比较,然后不断增加列索引,不断比较,没有的话就false。

    小于这个元素的话就在再从上一行开始比较,然后也不断增加索引,不断比较,没有的话就false。

    如果这个整数在里面,当到了判断:

                 elif target > array[r][c]:
                     c += 1

    这一步的条件不满足说明存在某个数大于等于这个整数,第一个出现的数肯定是等于这个整数的数,所以最后一种情况就是说找到了这个整数,返回True。

    c++

     1 class Solution {
     2 public:
     3     bool Find(int target, vector<vector<int> > array) {
     4         int row = array.size()-1;
     5         int col = array[0].size()-1;
     6         int r=row;
     7         int c=0;
     8         while(r>=0 && c<=col){
     9             if(target<array[r][c]) r--;
    10             else if(target>array[r][c]) c++;
    11             else return true;
    12         }
    13         return false;
    14     }
    15 };
  • 相关阅读:
    poj 2312 Battle City
    poj 2002 Squares
    poj 3641 Pseudoprime numbers
    poj 3580 SuperMemo
    poj 3281 Dining
    poj 3259 Wormholes
    poj 3080 Blue Jeans
    poj 3070 Fibonacci
    poj 2887 Big String
    poj 2631 Roads in the North
  • 原文地址:https://www.cnblogs.com/pacino12134/p/10938919.html
Copyright © 2011-2022 走看看