知识点:二维数组
最容易想到的思路,行列双重遍历查找
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
for row in array:
for num in row:
if num == target:
return True
return False
使用这种方法所用的时间和内存:
书上给出的解法,从右上角开始找:
if num > target: 去除该列(左移一位)
if num < target: 去除该行(下移一位)
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
if not array:
return False
row_num = len(array) # 行数
col_num = len(array[0]) # 列数
# 右上角元素
i = 0 # 第一行
j = col_num - 1 #最后一列
while i <= row_num - 1 and j >= 0:
if array[i][j] > target:
j -= 1 # 左移
elif array[i][j] < target:
i += 1 # 下移
elif array[i][j] == target:
return True
return False
试从左下角找,思路相似:
if num < target: 去除该列(右移一位)
if num > target: 去除该行(上移一位)
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
if not array:
return False
row_num = len(array) # 行数
col_num = len(array[0]) # 列数
# 左下角元素
i = row_num - 1 # 最后一行
j = 0 # 第一列
while i >= 0 and j <= col_num - 1:
if array[i][j] > target:
i -= 1 # 上移
elif array[i][j] < target:
j += 1 # 右移
elif array[i][j] == target:
return True
return False