def searchMatrix(self, matrix, target):
"""
容易出错的地方:二分查找的low<=high的条件
二维数组转化为一维数组的方法:
1.extend 循环n行
2.普通的二层循环
3. eval 表达式转化 去掉[]
...
"""
#n = len(matrix)###行
res = []
# for i in range(n):
# res.extend(matrix[i])
res = [i for item in matrix for i in item]
n = len(res)
low,high = 0,n-1
#mid = int((low+high)/2)
while low <= high:
mid = int((low+high)/2)
if target == res[mid]:
return True
elif target < res[mid]:
high = mid -1
else:
low = mid + 1
return False
'''
二维数组转化为一维数组的方法:
1.extend 循环n行
2.普通的二层循环
3. eval 表达式转化 去掉[]
4.itertools工具的方法chain
'''
from itertools import chain
b=[[1,2,3], [5,8], [7,8,9]]
c=list(chain(*b))
print(c)
[1, 2, 3, 5, 8, 7, 8, 9]
import operator
from functools import reduce
a = [[1,2,3], [4,6], [7,8,9,8]]
print(reduce(operator.add, a))
leetcode240
def searchMatrix(self, matrix, target):
"""
注意边界条件
从右上角开始如果小于该值减少这一列j--,如果大于该值,行增加i++
"""
if not matrix:
return False
if not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
i = 0
j = n - 1
while j < n and j >= 0 and i < m and i >=0:
if target < matrix[i][j]:
j -= 1
elif target > matrix[i][j]:
i += 1
else:
return True
return False