Write an efficient algorithm that searches for a
target
value in anm x n
integermatrix
. Thematrix
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.
Input: 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]], target = 5
Output: true
Input: 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]], target = 20
Output: false
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if len(matrix) == 0:
return False
row_len = len(matrix[0])
idx = -1
while matrix:
row = matrix.pop(0)
left = 0
right = row_len - 1
while left <= right:
mid = left + (right - left) // 2
if row[mid] > target:
right = mid - 1
elif row[mid] < target:
left = mid + 1
else:
idx = mid
break
if idx != -1:
return True
return False
Runtime: 156 ms, faster than 92.11% of Python3 online submissions for Search a 2D Matrix II.
Memory Usage: 19.1 MB, less than 99.94% of Python3 online submissions for Search a 2D Matrix II.
생각보다 빠른 시간이라 놀랐지만, 반대로 더 빠르게 할 수도 있을 거 같다
def searchMatrix2(self, matrix: List[List[int]], target: int) -> bool:
if len(matrix) == 0:
return False
matrix_len = len(matrix) - 1
row = 0
col = len(matrix[0]) - 1
while row <= matrix_len and col >= 0:
if target == matrix[row][col]:
return True
if target < matrix[row][col]:
# 더 작은 값과 비교하기 위해 열을 좌측으로 이동
col -= 1
elif target > matrix[row][col]:
# 더 큰 값과 비교하기 위해 행을 아래로 이동
row += 1
return False
Runtime: 168 ms, faster than 41.53% of Python3 online submissions for Search a 2D Matrix II.
Memory Usage: 19.2 MB, less than 99.94% of Python3 online submissions for Search a 2D Matrix II.
생각만큼 빠르지가 않고, 첫번째 시도 코드를 다시 돌려도 대동소이하다 코드 자체보다는 오히려 리트코드 서버의 실행 속도에 좌우되는 느낌
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
return any(target in row for row in matrix)
Runtime: 164 ms, faster than 62.63% of Python3 online submissions for Search a 2D Matrix II.
Memory Usage: 20.6 MB, less than 29.46% of Python3 online submissions for Search a 2D Matrix II.