Problem: 240. 搜索二维矩阵 II
文章目录
- 思路 & 解题方法
- 复杂度
- 暴力
- 二分
- bisect
- Z
思路 & 解题方法
暴力、二分、Z
复杂度
时间复杂度:
暴力: O ( m n ) O(mn) O(mn)
二分: O ( m l o g n ) O(mlogn) O(mlogn)
Z: O ( m + n ) O(m + n) O(m+n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
暴力
class Solution:def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:for x in matrix:for num in x:if num == target:return Truereturn False
二分
class Solution:def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:for x in matrix:left, right = 0, len(matrix[0]) - 1while left <= right:mid = (left + right) // 2if x[mid] > target:right = mid - 1elif x[mid] < target:left = mid + 1else:return Truereturn False
bisect
class Solution:def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:for x in matrix:idx = bisect.bisect_left(x, target)if idx < len(x) and x[idx] == target:return Truereturn False
Z
class Solution:def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:m, n = len(matrix), len(matrix[0])x, y = 0, n - 1while x < m and y >= 0:if matrix[x][y] == target:return Trueif matrix[x][y] > target:y -= 1elif matrix[x][y] < target:x += 1return False