题目描述:
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
解题思路:
直接安排二分查找,将二维数组因为是有序的,抽象成一维数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: rows=len(matrix) if rows==0: return False cols=len(matrix[0]) left=0 right=rows*cols-1 while left<=right: mid = (right + left) // 2 element=matrix[mid//cols][mid%cols] if element==target: return True else: if target>element: left=mid+1 else: right=mid-1 return False
|