剑指offer-Python-01-二维数组中的查找

题目描述

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


思路:选取数组中右上角的数字:

  • 若该数字等于要查找的数字则查找结束。
  • 若该数字小于要查找的数字
    • 剔除这个数字所在行(因为右上角的数字该行最大,所以要查找的数字不在该行)
  • 若该数字大于要查找的数字
    • 剔除这个数字所在列(因为右上角的数字该行最小,所以要查找的数字不在该列)

这样不断的缩小查找范围,直到找到要查找的数字,或者查找范围为空

参考代码如下:

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        rows, columns = len(array)-1 , len(array[0]) - 1
        row = 0
        column = columns
        while row <= rows and column >= 0:
            if array[row][column] > target:
                column -= 1
            elif array[row][column] < target:
                row += 1
            else:
                return True
        return False

选取数组中左下的的数字:

  • 若该数字等于要查找的数字则查找结束。
  • 若该数字大于要查找的数字
    • 剔除这个数字所在列(因为左下角的数字该列最大,所以要查找的数字不在该列)
  • 若该数字小于要查找的数字
    • 剔除这个数字所在行(因为左下角的数字该行最小,所以要查找的数字不在该行)
# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        rows, columns = len(array)-1, len(array[0])-1
        row = rows
        column = 0
        while row >= 0 and column <=columns:
            if array[row][column] > target:
                row -= 1
            elif array[row][column] < target:
                column += 1
            else:
                return True
        return False

猜你喜欢

转载自blog.csdn.net/weixin_39223665/article/details/89467073