二维数组中查找值
2018-05-06 本文已影响0人
vckah
题目描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:
[1 2 8 9] 其中要寻找 7
[2 4 9 12] 从右上角开始,判断其是否大于 7,大于则说明 7 只可能出现在前三列,
[4 7 10 13] 如果小于则只可能出现在后三行
[6 8 11 15] 每次都只判断右上角的值
具体代码:
def find(target, array):
found = False
rows = len(array)
columns = len(array[0])
if rows>0 and columns>0:
row = 0
column = columns - 1
while row < rows and column >= 0:
if array[row][column] == target:
found = True
break
elif array[row][column] > target:
column -= 1
else:
row += 1
return found
def main():
test_martix = [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
target = 7
found = find(target, test_martix)
if found:
print('Found the target!')
if __name__ == '__main__':
main()