Problem : https://leetcode.com/problems/search-a-2d-matrix-ii/
Because each row and column is sorted in ascending order. One number is always larger than the number on its left and smaller than the number underneath. We can iterate from the top-right number. If the number is larger than the target, move the point to left side. If the number is smaller than the target value, move the point to down side.
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
ROW = len(matrix)
if ROW == 0:
return False
COL = len(matrix[0])
if COL == 0:
return False
if target < matrix[0][0] or matrix[-1][-1] < target:
return False
y = 0
x = COL - 1
while x >= 0 and y < ROW:
if matrix[y][x] > target:
# move pointer to left side
x -= 1
elif matrix[y][x] < target:
# move pointer to down side
y += 1
else:
return True
return False
No comments:
Post a Comment