题目描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
python代码实现:
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
if len(array) == 0:
return False
row = len(array)
col = len(array[0])
i = 0
j = col -1
while i < row and j >= 0:
if array[i][j] > target:
j -= 1
elif array[i][j] < target:
i += 1
else:
return True
return False
解析:因为数组是横向和纵向递增的,因此查找时不需要蛮力查找
1 2 3 4 5
3 4 5 7 8
4 5 6 8 9
7 8 9 10 11
可以从右上角开始比较,假设要找的数字是6,先与右上角的5比较,5比6小,因此向下一行;8比6大,因此向左一列;7比6大,因此向左一列;5比6小,因此向下一行;6=6,返回True