剑指offer 编程题 -- 二维数组中的查找

题目描述

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

方法1

直接进行穷举搜索。

class Solution {

public:

    bool Find(int target, vector<vector<int> > array) {

      for(size_t i=0;i<array.size();i++){

          for (size_t j = 0;j<array[i].size();j++){

              if(target == array[i][j]){

                  return true;

              }            

          }        

      }

      return false;

}

};

运行时间:12ms

占用内存:1476k

方法2

考虑行和列的递增条件,如下表所示,

1

3

5

10

15

2

6

7

11

16

4

9

13

16

19

5

20

22

25

30

 

因为右边的数均比左边的大,下边的数均比上边的大,考虑可以从右上角开始查找。

比如查找上表中的20,从15开始查找,

20 > 15,因此行+1;

20 > 16,因此行+1;

20 > 19,因此行+1;

20 < 30,因此列-1;

20 < 25,因此列-1;

20 < 22,因此列-1。

总之,如果要查找的数比每行中最大的数还要大,则行加1;如果要查找的数比旁边的数小,则列减1。

class Solution {

public:

    bool Find(int target, vector<vector<int> > array) {

        int rows = array.size();

        int cols = array[0].size();

        int  i=0,j = cols -1;

      while(i<rows && j >= 0){

          if(target == array[i][j]){

              return true;

          }

          else if(target > array[i][j]){

              i++;          

          }

          else if(target < array[i][j]){

              j--;

          }        

      }

        return false; 

}

};

运行时间:11ms

占用内存:1480k

 

参考链接:

https://blog.csdn.net/qq_38845858/article/details/81259984

 

猜你喜欢

转载自blog.csdn.net/mmg188/article/details/84791472