python
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# 把距阵变成列表,然后二分查找
nums=[]
m=len(matrix)
n=len(matrix[0])
for i in range(m):
for j in range(n):
nums.append(matrix[i][j])
left,right=0,len(nums)-1
if target<nums[0] or target>nums[right]:
return False
while left<=right:
mid=left+(right-left)//2
if target==nums[mid]:
return True
elif target<nums[mid]:
right=mid-1
else:
left=mid+1
return False
思路:
- 暴力求解
- 把矩阵降维,然后使用二分搜索
列表推导式
将二维数组变为一维数组中,使用列表推导式,会更加简便
python
# 二维矩阵
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 将二维矩阵转换为一维列表
flat_list = [element for row in matrix for element in row]
print(flat_list)
解法二:
python
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m=len(matrix)
n=len(matrix[0])
i,j=0,m*n-1
while i<=j:
mid=i+(j-i)//2
x=mid // n
y=mid % n
if target==matrix[x][y]:
return True
elif target<matrix[x][y]:
j=mid-1
else:
i=mid+1
return False
思路:
- 同样是二分查找,把mid对应的二维坐标找到就可以了