Programming/LeetCode
[LeetCode] Search a 2D Matrix
데이터현
2022. 3. 30. 14:59
https://leetcode.com/problems/search-a-2d-matrix/
Search a 2D Matrix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
정렬되어 있는 게 이진 탐색으로 풀어주세요~ 하는 조건이다.
데이터는 매트릭스 형태이기 때문에 이에 맞춰 수정해주면 된다.
재귀로 풀었다.
나의 풀이
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])
def search(start, end):
if start>end:
return False
mid = (start + end)//2
x, y = mid//n, mid%n
if matrix[x][y] == target:
return True
elif matrix[x][y] > target:
return search(start, mid-1)
else:
return search(mid+1, end)
return search(0, m*n-1)