취미가 좋다

240. Search a 2D Matrix II 본문

알고리즘 문제풀이/Leetcode

240. Search a 2D Matrix II

benlee73 2021. 10. 2. 20:37

https://leetcode.com/problems/search-a-2d-matrix-ii/

 

Search a 2D Matrix II - 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

Solution

class Solution:
    def searchMatrix(self, matrix, target):
        row, col = 0, len(matrix[0])-1
        while row < len(matrix) and col >= 0:
            if matrix[row][col] < target:
                row += 1
            elif matrix[row][col] > target:
                col -= 1
            else:
                return True
        return False
  • 우측 위부터 시작한다.
  • 타겟보다 작으면 row를 증가시키고 타겟보다 크면 col을 감소시킨다.
  • 타겟을 만나면 True를 반환하고 못만나면 False를 반환한다.

 

  • 원래 풀고 싶은 방법
    • 대각선을 살피면서 타겟보다 커지는 지점을 찾는다.
    • 행렬을 쪼개서 타겟이 있을 만한 곳을 같은 방법(재귀)으로 찾는다.
    • 재귀가 너무 깊어서 에러가 발생한다.

'알고리즘 문제풀이 > Leetcode' 카테고리의 다른 글

31. Next Permutation  (0) 2021.10.08
239. Sliding Window Maximum  (0) 2021.09.28
238. Product of Array Except Self  (0) 2021.09.24
236. Lowest Common Ancestor of a Binary Tree  (0) 2021.09.22
230. Kth Smallest Element in a BST  (0) 2021.09.07
Comments