Leetcode 74 and 240. Search a 2D matrix I and II

时间:2022-04-08 18:33:53

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.

For example,

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given target = 3, return true.

第一题的条件比第二题还强,也就是本行的第一个元素比上一行的最后一个元素要大。所以如果第一题把2D矩阵拉平成一个1D list,这个list是一个sorted list。可以再用二分法查找。

 class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False nums = []
for elem in matrix:
nums += elem
n = len(nums) low, high = 0, n-1
while low <= high:
mid = (low+high)//2
if target < nums[mid]:
high = mid -1
elif target > nums[mid]:
low = mid + 1
else:
return True
return False

如果不把2D matrix转换成1D array,可以直接操作row 和 col。注意L17-L18的对于从1D的位置到row col的转换方法。

 class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False m = len(matrix)
n = len(matrix[0])
l , r = 0, n*m -1 while l <= r:
mid = l + (r - l)/2
row = mid/ n
col = mid% n
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
l = mid + 1
else:
r = mid - 1
return False

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

第二题不能像第一题那样把2D matrix拉成一个1D list。可以使用类似kth smallest element in a sorted matrix中的类似查找方法。

 def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m, n = len(matrix), len(matrix[0])
i, j = m - 1, 0 while i >= 0 and j < n:
if matrix[i][j] > target:
i -= 1
elif matrix[i][j] < target:
j += 1
else:
return True
return False