原题
https://leetcode.cn/problems/search-a-2d-matrix/description/
思路
二分查找
复杂度
时间:O(m * log(n))
空间:O(1)
Python代码
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])
for i in range(m):
if target > matrix[i][-1]:
continue
l = 0
r = n
while l < r:
mid = (l + r) // 2
if target == matrix[i][mid]:
return True
elif target > matrix[i][mid]:
l = mid + 1
else:
r = mid
return False
Go代码
func searchMatrix(matrix [][]int, target int) bool {
m, n := len(matrix), len(matrix[0])
for i := 0; i < m; i++ {
if target > matrix[i][n-1] {
continue
}
l, r := 0, n
for l < r {
mid := (l + r) / 2
if target == matrix[i][mid] {
return true
} else if target > matrix[i][mid] {
l = mid + 1
} else {
r = mid
}
}
}
return false
}

被折叠的 条评论
为什么被折叠?



