牛客66道编程题——二维数组中的查找

题目

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

方法一:直接法1

class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        if array==[[]]: #判断列表是否为空列表
            return False
        l=len(array)
        for i in range(l):
            if target in array[i]:#判断target是否在array的第i行中
                return True

方法二:直接法2

class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        if array==[[]]:
            return False
        r=len(array)#获取二维数组的行数
        l=len(array[0])#获取二维数组的列数
        for i in range(r):
            for j in range(l):
                if target == array[i][j]:
                    return True

方法三:左下角开始查找法

由于二维数组是有序的,因此从左下角开始看,往上数字是递减的,往右数字是递增的,因此便有了如下算法。

第一种写法

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

第二种写法

class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        #其它方法
        if array==[[]]:
            return False
        elif target<array[0][0] or target>array[-1][-1]:
            return False
        else:
            r=len(array)
            l=len(array[0])
            for i in range(r-1,-1,-1):
                if target>=array[i][0]:
                    for j in range(0,l):
                        if target==array[i][j]:
                            return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值