在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
if array is None:
return False
row = len(array)
col = len(array[0])
for i in range(row):
for j in range(col):
if target == array[i][j]:
return True
return False
最低级的方法就算循环了,暴力破解
另一种方法:
1. 选取数字中右上角的数字,如果该数字等于要查找的数字,则查找过程结束
2. 如果该数字大于要查找的数字,则剔除这个数字所在的列
3. 如果该数字小于要查找的数字,则剔除这个数字所在的行
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
row = 0
col = len(array[0])
while(row < len(array) and col>0):
if array[row][col-1] == target:
return True
if array[row][col-1] > target:
col = col-1
if array[row][col-1] < target:
row = row+1
return False