美文网首页
offer04二维数组中的查找python

offer04二维数组中的查找python

作者: D_w | 来源:发表于2020-02-24 20:47 被阅读0次

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

    解答思路

    该二维数组的第一行最后一列的元素很有特点,其左边的数依次小于他,其下面的数依次大于他,因此可以通过该数来缩小查找区间,目标元素小于他则向左找,若大于他则向下找
    python

    # -*- coding:utf-8 -*-
    class Solution:
        # array 二维列表
           def Find(self, target, array):
                 if array == []:
                     return False #数组为空则返回错误
             row = len(array) #取数组的行数
             clown = len(array[0]) #取数组的列数
              i = clown - 1 #最左边数的下标为列数减一
              j = 0
              while i>=0 and j < row: #从第一行最左边开始循环
                  if array[j][i] > target: #目标数小于array[j][i] 时
                      i-=1 #向左取数
                  elif array[j][i] < target: #目标数大于array[i][j]时
                      j += 1 #向下取数
                  else:#若等于该数则返回
                      return True #等价于 return array[j][i]
    

    java

    class Solution {
        public boolean findNumberIn2DArray(int[][] matrix, int target) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return false;
            }
            int row = matrix.length;
            int clo = matrix[0].length;
            int i = 0;
            int j = clo-1;
            while (i<row && j>=0){
                if (target < matrix[i][j]){
                    j--;
                }else if (target > matrix[i][j]){
                    i++;
                }else return true;
            }
            return false;
        }
    }
    

    相关文章

      网友评论

          本文标题:offer04二维数组中的查找python

          本文链接:https://www.haomeiwen.com/subject/uzxqchtx.html