class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
ROWS = len(matrix)
COLS = len(matrix[0])
l, r = 0, COLS*ROWS - 1
while l<=r:
mid = (l+r)//2
rr = mid // COLS
cc = mid % COLS
if matrix[rr][cc] < target:
l = mid+1
elif matrix[rr][cc] > target:
r = mid-1
else:
return True
return False
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
def bst(arr, t):
l, r = 0, len(arr)-1
while(l<=r):
m = (l+r)//2
"""
아래 부분.. 주의!!.. 자주 틀림!!
if arr[m] < t:
l = m+1
elif t < arr[m]:
r = m-1
"""
if arr[m] < t:
l = m+1
elif t < arr[m]:
r = m-1
else:
return True
return False
for mm in matrix:
if mm[0] <= target and target <= mm[-1]:
ck = bst(mm, target)
if ck == True:
return True
return False
최종 코드
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
rows, cols = len(matrix), len(matrix[0])
left, right=0, rows*cols-1
while left<=right:
m = (left+right)//2
r = m // cols
c = m % cols
if matrix[r][c] < target:
# 커져야 함
left = m+1
elif matrix[r][c] > target:
# 작아져야 함
right = m-1
else:
return True
return False
'LeetCode > NeetCode' 카테고리의 다른 글
[Two Heaps] Heap-PrioiryQueue: 295. Find Median from Data Stream ★★★ (0) | 2024.12.22 |
---|---|
[Two Heap] 502. IPO ★★★★★ (0) | 2024.12.22 |
[카데인 Kadane] 918. Maximum Sum Circular Subarray ★★★ (0) | 2024.12.20 |
[카데인 Kadane] 53. Maximum Subarray (0) | 2024.12.20 |
위상정렬: Graphs (싸이클탐지): 210. Course Schedule II★ (2) | 2024.12.17 |