본문으로 바로가기

[LeetCode]74. Search a 2D Matrix

category 코딩테스트/LeetCode 2022. 11. 3. 00:32

https://leetcode.com/problems/search-a-2d-matrix/description/?envType=study-plan&id=algorithm-ii 

 

Search a 2D Matrix - 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과 같이 2차원 배열과 target 이 주어졌을때, target 값이 있는지 참/거짓을 알아내는 문제이다.

즉,  2차원 배열에서 이분탐색하기 

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        
       if(matrix == null || matrix.length==0 || matrix[0].length==0) return false;

       int col = matrix.length;
       int row = matrix[0].length;

       int start = 0;
       int end = col*row-1;

       while(start <= end){
           int mid = (start + end)/2;
           int midCol = mid/row;
           int midRow = mid%row;

           if(matrix[midCol][midRow] == target){
               return true;
           } else if(matrix[midCol][midRow] < target){
               start = mid+1;
           } else {
               end = mid-1;
           }
 
       }

       return false;
    }
}