题目:
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:
遍历每一行,查找该元素是否在该行之中。
解答
方法一
class Solution:
def Find(self, target, array):
for line in array:
if target in line:
return True
return False
思路
有序,从右上角开始比较,一次少一行或一列
方法二
class Solution:
def Find(self, target, array):
i = 0
j = len(array[0])-1
while i < len(array) and j >= 0:
if array[i][j] == target:
return True
elif array[i][j] > target:
j -= 1
else:
i += 1
return False