这一题其实也没啥好说的,就是一个走迷宫的问题。利用分治的思想,将大问题分解为一步步的小问题,关键还是如何分和几个特解的关注:
两种思路:
1.从左下开始走,对于上方元素比他小,对于右方元素比他大,官网经典思路
python3代码
class Solution:
def Find(self, target: int, array: List[List[int]]) -> bool:
# 无行无列
if len(array) == 0:
return False
# 有一行但为空
if len(array[0]) == 0:
return False
# 开始正常走,向右走,判断列好了
n = len(array[0])
i = len(array) - 1
j = 0
# 数组下标,确定搜索区域
while i >= 0 and j <= n - 1:
if array[i][j] > target:
i = i - 1
elif array[i][j] < target:
j = j + 1
else:
# 找到了
return True
# 二维数组找完了,没找到
return False
第二个思路,从右上开始找,基本一样,只不过规则和判断依据有点不一样,直接贴代码了:
class Solution:
def Find(self , target: int, array: List[List[int]]) -> bool:
# write code here
if len(array)==0:
return False
n=len(array)
if len(array[0])==0:
return False
#列数
m=len(array[0])
#行数
n=len(array)
i=0
j=m-1
while i<n and j>=0:
if array[i][j]>target:
j-=1
elif array[i][j]<target:
i+=1
else:
return True
return False