[LeetCode]Search a 2D Matrix II

2024. 3. 24. 15:59·SW개발/코딩테스트

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

문제 분석

주어진 m*n 2D Matrix에서 원하는 target 값이 있는지 찾는 문제입니다.

 

처음 시도한 답안

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for m in matrix:
            left = 0
            right = len(m)-1

            while left <= right:
                mid = (left+right) // 2

                if m[mid] == target:
                    return True
                
                if m[mid] > target:
                    right -= 1
                else: 
                    left +=1

        return False

접근 방법

  1. matrix의 행을 순회하면서 이분 탐색을 진행합니다.
    1. 행에서 숫자의 연속성을 확인할 수 없으므로, 행마다 이분 탐색을 반복하여 target값을 찾으면 됩니다.
  2. 기본적인 이분 탐색을 진행합니다.
    1. left와 right값을 설정하고 중간값인 mid를 설정합니다.
    2. 만약 target을 찾았다면 True를 리턴합니다.
    3. mid값이 target보다 크다면 right를 -1하여 왼쪽을 탐색합니다.
    4. mid값이 target보다 작다면 left를 +1하여 오른쪽을 탐색합니다.
  3. 행을 모두 반복해도 target을 찾지 못했다면 존재하지 않는 것이므로 False를 리턴합니다.

행의 수만큼 개별적으로 이분 탐색을 진행하면 손쉽게 풀이할 수 있습니다.

 

이전에 풀이한 문제와 굉장이 유사합니다. 행에서 연속된 숫자가 아니란 점이 다른 점입니다. 

https://leffept.tistory.com/499

 

[LeetCode]Search a 2D Matrix

https://leetcode.com/problems/search-a-2d-matrix/description/ 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 sorte

leffept.tistory.com

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Product of Array Except Self  (0) 2024.03.26
[LeetCode]Find the Duplicate Number  (2) 2024.03.25
[LeetCode]Kth Smallest Element in BST  (0) 2024.03.23
[Leetcode]Kth Largest Element in an Array  (0) 2024.03.22
[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal  (0) 2023.06.02
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Product of Array Except Self
  • [LeetCode]Find the Duplicate Number
  • [LeetCode]Kth Smallest Element in BST
  • [Leetcode]Kth Largest Element in an Array
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    오픈소스
    Contributor
    음식
    배달
    g
    배달비 공유
    django
    컨트리뷰터
    배공파용
    어플리케이션
    플레이스토어
    트리 #AVL #알고리즘 #자료구조
    라이프 스타일
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Search a 2D Matrix II
상단으로

티스토리툴바