Algorithm/1일 1코테

[💕 LeetCode Python] 240. Search a 2D Matrix 2

대인보우 2020. 10. 26. 20:10
반응형

240. 

Search a 2D Matrix 2

 


문제

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

 

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

 

내가 쓴 답

def searchMatrix(self, matrix, target):
        for i in matrix:
            if target in i:
                return True
        return False

 

풀이

def searchMatrix(self, matrix, target):
        return any(target in row for row in matrix)
def searchMatrix(self, matrix, target):

        if not matrix: #matrix에 값이 없을 경우
            return False
        
        #-----------------------------
        
        row = 0
        col = len(matrix[0])-1
        
        while row <= len(matrix)-1 and col >= 0:    
            if target < matrix[row][col]:
                col -= 1
            elif target > matrix[row][col]:
                row += 1
            else:
                return True
        return False
반응형