1. 程式人生 > >leetcode 74. 搜尋二維矩陣 &

leetcode 74. 搜尋二維矩陣 &

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))