Problem: 240. 搜索二维矩阵 II
思路 & 解题方法
暴力、二分、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 True
return False
二分
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for x in matrix:
left, right = 0, len(matrix[0]) - 1
while left <= right:
mid = (left + right) // 2
if x[mid] > target:
right = mid - 1
elif x[mid] < target:
left = mid + 1
else:
return True
return 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 True
return 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 - 1
while x < m and y >= 0:
if matrix[x][y] == target:
return True
if matrix[x][y] > target:
y -= 1
elif matrix[x][y] < target:
x += 1
return False