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 sorted in non-decreasing order. * The first integer of each row is greater than the last integer
leetcode.com
< 문제 간단설명 >
주어진 2차원 배열에서 target 값이 존재하는지 찾는 문제이다.
그냥 간단히 할 수도 있겠지만... topic이 Binary Search인 만큼 이진탐색으로 찾아보았다.
/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target) {
    let [row, col] = [0, matrix[0].length - 1];
    let cur = 0;
    while(row < matrix.length && col >= 0) {
        cur = matrix[row][col];
        if(cur === target) {
            return true;
        }
        if(cur < target) {
            row += 1;
        }
        if(cur > target) {
            col -= 1;
        }
    }
    return false;
};'PS > LeetCode' 카테고리의 다른 글
| LeetCode / Binary Search Tree / 108번 / Convert Sorted Array to Binary Search Tree / JS (0) | 2023.04.29 | 
|---|---|
| LeetCode / Binary Search / 33번 / Search in Rotated Sorted Array / JS (0) | 2023.04.28 | 
| LeetCode / Tree / 437번 / Path Sum III / JS (0) | 2023.04.28 | 
| LeetCode / Tree / 543번 / Diameter of Binary Tree / JS (0) | 2023.04.28 |