题目
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
方法一:直接法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