难度: Medium
原题连接
内容描述
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
思路 1 - 时间复杂度: O(lg(row * col))- 空间复杂度: O(1)******
将2D matrix
看成一个大sorted list
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
row = len(matrix)
col = len(matrix[0]) if row else 0
l, r = 0, row * col - 1
while l <= r:
mid = l + ((r - l) >> 2)
if target > matrix[mid//col][mid%col]:
l = mid + 1
elif target < matrix[mid//col][mid%col]:
r = mid - 1
else:
return True
return False
但是后面觉得这样不好, 原因如下:
- m * n may overflow for large m and n;
- it will use multiple expensive operations such as / and %
思路 2 - 时间复杂度: O(lg(row) + lg(col))- 空间复杂度: O(1)******
因此二分Search, binary search by row first, then binary search by column.
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
row = len(matrix)
col = len(matrix[0]) if row else 0
l, r = 0, row - 1
while l <= r:
mid_row = l + ((r - l) >> 2)
if matrix[mid_row][0] <= target <= matrix[mid_row][-1]:
m, n = 0, col - 1
while m <= n:
mid_col = m + ((n - m) >> 2)
if matrix[mid_row][mid_col] > target:
n = mid_col - 1
elif matrix[mid_row][mid_col] < target:
m = mid_col + 1
else:
return True
return False
elif target < matrix[mid_row][0]:
r = mid_row - 1
else:
l = mid_row + 1
return False