classSolution: defmySqrt(self, x: int) -> int: left, right = 0, x while left <= right: mid = left + (right -left)//2 if mid*mid == x: return mid elif mid*mid < x: left = mid + 1 else: right = mid -1 return right
搜索二维矩阵(力扣74)
思路:将矩阵拉平之后就是一个基本的二分查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defsearchMatrix(self, matrix: List[List[int]], target: int) -> bool: temp = [j for i in matrix for j in i] return self.binear_search(temp, target) defbinear_search(self, nums, target): left, right = 0, len(nums)-1 while left <= right: mid = (left + right)//2 if nums[mid] == target: returnTrue elif nums[mid] < target: left = mid + 1 else: right = mid - 1 returnFalse
空间复杂度为1的算法思路:
这里最重要的是要记住一点,拉平之后的索引在原矩阵中的位置为:
row = idx // n col = idx % n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defsearchMatrix(self, matrix: List[List[int]], target: int) -> bool: ifnot matrix ornot matrix[0]: returnFalse m = len(matrix) n = len(matrix[0]) left, right = 0, m*n-1 while left <= right: mid = (left + right) // 2 value = matrix[mid//n][mid%n] if value == target: returnTrue elif value > target: right = mid - 1 else: left = mid + 1 returnFalse