matrix 2. 이분탐색
matrix 2. 이분탐색 — #LeetCode #개발자의도구들 #2d이분탐색 #matrix이분탐색 only 파이썬 목표 참고 : 여기 전략생각하기 정...
#LeetCode#Naver Blog
#LeetCode #개발자의도구들 #2d이분탐색 #matrix이분탐색
- only 파이썬
- 목표 참고 : 여기
전략생각하기
LeetCode(medium 110. Balanced Binary Tree)
📌 각 row의 최솟값은 이전 row의 최댓값 보다 크다.
📌 m x n matrix
🤩 follow up O(log(m * n))
🤔 정렬 + log(n * m)인 것을 보면 뭔가 이분 탐색 같다.
👉 이분 탐색을 row, col 각각 한번 씩 진행하면 된다.
👉 pointer를 4개 두기
👉 row를 먼저 탐색하기
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
# row check
rs = 0
re = len(matrix) - 1
rt = 999
while rs <= re:
mid = (rs + re) / 2
if matrix[mid][0] <= target <= matrix[mid][-1]:
rt = mid
break
if target > matrix[mid][-1]:
rs = mid + 1
elif target < matrix[mid][0]:
re = mid - 1
if rt == 999:
return False
cs = 0
ce = len(matrix[0]) - 1
isFound = False
while cs <= ce:
targetRow = matrix[rt]
mid = (ce + cs) / 2
if target == targetRow[mid]:
return True
if target > targetRow[mid]:
cs = mid + 1
elif target < targetRow[mid]:
ce = mid - 1
return False
- 정답이다!
- t: O(log(mxn) Beats 100%
- s: O(1) Beats 59.8%
- 처음에 row에서 못찾았을 때를 고려하지 않아서 한번 실패했다.