题目来源
https://leetcode.com/problems/search-a-2d-matrix/description/
题目描述
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
给出一个矩阵, 每行都是升序排列的, 而且保证第 i+1 行的第一个元素大于第 i 行的最后一个元素.
解题思路
这不过是一个二维数据结构的查找而已, 查找最简单高效的方法便是二分法.
我们只需先用第一次二分查找找出元素可能会在哪一行, 再用第二次二分查找找出元素可能在哪一具体位置即可.
代码实现
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
M=len(matrix)
if M==0:
return False
N = len(matrix[0])
if N==0:
return False
lo=0
hi=M-1
while lo<=hi:
mid=int((lo+hi)/2)
if matrix[mid][0]==target:
return True
elif matrix[mid][0]>target:
hi=mid-1
else:
lo=mid+1
# print(lo,hi)
if lo==0 or lo==M+1:
return False
temp=hi
lo=0
hi=N-1
# print(temp,mid)
while lo<=hi:
mid=int((lo+hi)/2)
if matrix[temp][mid]==target:
return True
elif matrix[temp][mid]>target:
hi=mid-1
else:
lo=mid+1
return False
代码表现
看到代码表现的很优秀, 博主表示很开心( ̄▽ ̄)~*