74. Search a 2D Matrix, 자바 풀이

이원석·2023년 9월 1일

Leetcode

목록 보기
9/22
post-thumbnail

[문제]
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 of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.

You must write a solution in O(log(m * n)) time complexity.

https://leetcode.com/problems/search-a-2d-matrix/?envType=study-plan-v2&envId=top-interview-150


class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        ArrayList<Integer> list = new ArrayList<>();

        for (int[] m : matrix) {
            for (int n : m) {
                list.add(n);
            }
        }

        int s = 0;
        int e = list.size() - 1;

        while (s <= e) {
            int mid = (s + e) / 2;

            if (list.get(mid) < target) {
                s = mid + 1;
            } else if (list.get(mid) > target) {
                e = mid - 1;
            } else {
                return true;
            }
        }

        return false;
    }
}

주어진 2차원 배열에서 target 값을 찾는 문제이다. 이차원 배열을 모두 분해하여 list에 값들을 저장 후, 이분탐색을 활용했다.

0개의 댓글