240. Search a 2D Matrix II

2021. 5. 18. 10:03·Algorithm
 

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

1. Brute Force

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        temp = []
        for item in matrix:
            temp += item
        if target in temp:
            return True
        return False

그냥 이렇게 배열을 정말 탐색해도 통과는 된다.

2. 이진 탐색

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not matrix:
            return False
        row, col = 0, len(matrix[0]) - 1
        while 0 <= row < len(matrix) and 0 <= col < len(matrix[0]):
            temp = matrix[row][col]
            if temp == target:
                return True
            elif temp > target:
                col -= 1
            elif temp < target:
                row += 1
        return False

정렬이 되어있는데 탐색을 해야 한다면 이진 탐색을 한번 생각해보면 좋다.

행, 열 모두 오름차순으로 정렬되어있기 때문에 위 풀이가 가능하다.

 

이진 탐색은 생각했지만 예쁘게 푸는 법을 스스로 찾진 못했다.

'Algorithm' 카테고리의 다른 글

300. Longest Increasing Subsequence  (0) 2021.05.19
208. Implement Trie (Prefix Tree)  (0) 2021.05.18
279. Perfect Squares  (0) 2021.05.17
236. Lowest Common Ancestor of a Binary Tree  (0) 2021.05.17
200. Number of Islands  (0) 2021.05.17
'Algorithm' 카테고리의 다른 글
  • 300. Longest Increasing Subsequence
  • 208. Implement Trie (Prefix Tree)
  • 279. Perfect Squares
  • 236. Lowest Common Ancestor of a Binary Tree
Doljae
Doljae
  • Doljae
    Zero to Hero
    Doljae
  • 전체
    오늘
    어제
    • 분류 전체보기 (349)
      • Programming (54)
      • Algorithm (161)
      • Review (102)
      • Career (8)
      • Diary (18)
      • Shorts (4)
      • Temp (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글 쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    database
    db
    코딩테스트
    나는리뷰어다
    컨퍼런스
    AI
    java
    개발자
    라인
    sql튜닝
    코딩
    PYTHON
    공채
    leetcode
    백준
    mysql
    인프콘
    2022
    line
    면접
    한빛미디어
    jpa
    프로그래머스
    2023
    ChatGPT
    BOJ
    회고
    2021
    sql
    나는 리뷰어다
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Doljae
240. Search a 2D Matrix II
상단으로

티스토리툴바