PS/LeetCode
LeetCode / Binary Search / 74번 / Search a 2D Matrix / JS
KimMinJun
2023. 4. 28. 17:41
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;
};