leetcode 74. 搜尋二維矩陣 &240. 搜尋二維矩陣 II
阿新 • • 發佈:2018-11-09
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