74. Search a 2D Matrix
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
解题要点:
把整个2d数组看作一条1d数组,长度可以计算为n * m - 1。然后用二分算法搜素目标数字。
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
n = len(matrix)
if n == 0:
return False
m = len(matrix[0])
if m == 0:
return False
l = 0
h = m * n - 1
while l <= h:
mid = l + (h-l) / 2
i = mid / m
j = mid % m
if matrix[i][j] == target:
return True
elif matrix[i][j] < target:
l = mid + 1
else:
h = mid - 1
return False
Last updated
Was this helpful?