본문 바로가기

자료구조,알고리즘

LeetCode-74 Search a 2D Matrix 파이썬 풀이

 

Search a 2D Matrix - LeetCode

Can you solve this real interview question? Search a 2D Matrix - You are given an m x n integer matrix matrix with the following two properties: * Each row is sorted in non-decreasing order. * The first integer of each row is greater than the last integer

leetcode.com

문제

이차원 배열안에서 target값이 존재하는 지를 찾는 문제 입니다.

풀이

단순히 이차원 배열을 한행씩 쪼개어 in 연산을 통해 쉽게 해결하였습니다. 

각 행의 순서가 오름차순으로 배치되어있기 때문에 in 연산자를 사용하지 않고 이진 탐색을 통해서도 충분히 해결할 수 있습니다.

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for i in range(0,len(matrix)):
            if target in matrix[i]:
                return True
        return False