๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ/LeetCode

[LeetCode] Search A 2d Matrix II

๋ฌธ์ œ๋งํฌ

 

Search a 2D Matrix II - 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

 

ํ–‰์„ ๊ธฐ์ค€์œผ๋กœ๋„ ์—ด์„ ๊ธฐ์ค€์œผ๋กœ๋„ ๋ชจ๋‘ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ 2์ฐจ์› ๋ฐฐ์—ด์ด ์žˆ๋‹ค.
์ด๋•Œ ์ฃผ์–ด์ง„ target ์ˆซ์ž๊ฐ€ ํ–‰๋ ฌ์— ์กด์žฌํ•˜๋Š”์ง€ ๊ตฌํ•˜์—ฌ๋ผ.

์ ‘๊ทผ ๋ฐฉ๋ฒ•

-10^9 <= matrix[i][j] <= 10^9 ํฌ๊ธฐ์˜ ๋งค์šฐ ํฐ ๋ฐฐ์—ด์ด๋ฏ€๋กœ forEach, includes๋ฅผ ์‚ฌ์šฉํ•œ O(n^2) ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค.

ํ–‰์œผ๋กœ๋„ ์—ด๋กœ๋„ ์˜ค๋ฆ„์ฐจ์ˆœ์„ ๋งŒ์กฑํ•˜๋Š” ๋ฐฐ์—ด์ด๋ฏ€๋กœ ์ •๋ฆฌํ•˜์ž๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

์™ผ์ชฝ ์ƒ๋‹จ ๋ : ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜
์˜ค๋ฅธ์ชฝ ์ƒ๋‹จ ๋ : 0ํ–‰์ค‘ ๊ฐ€์žฅ ํฌ๊ณ  ๋งˆ์ง€๋ง‰ ์—ด ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜
์™ผ์ชฝ ํ•˜๋‹จ ๋ : 0์—ด์ค‘ ๊ฐ€์žฅ ํฌ๊ณ  ๋งˆ์ง€๋ง‰ ํ–‰ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜
์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ ๋ : ๊ฐ€์žฅ ํฐ ์ˆ˜

๊ฐ€์žฅ ํฐ์ˆ˜์™€ ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜์ธ ๊ฒฝ์šฐ target๊ฐ’๊ณผ ๋น„๊ตํ–ˆ์„๋•Œ ํ–‰์„ ์ด๋™ํ• ์ง€, ์—ด์„ ์ด๋™ํ• ์ง€ ์„ ํƒํ•˜๋Š”๋ฐ ๋˜ ์กฐ๊ฑด์ด ํ•„์š”ํ•˜์—ฌ ๋ณต์žกํ•˜๋‹ค. (matrix[0][0] < target ์ธ ๊ฒฝ์šฐ matrix[0][1]๋กœ ์ด๋™ํ• ์ง€ matrix[1][0]์œผ๋กœ ์ด๋™ํ• ์ง€ ์• ๋งคํ•˜๋‹ค.)

๋•Œ๋ฌธ์— ์˜ค๋ฅธ์ชฝ ์ƒ๋‹จ ๋ ๋˜๋Š” ์™ผ์ชฝ ํ•˜๋‹จ ๋๋ถ€ํ„ฐ ์ด๋™ํ•ด์•ผ์ง€ ๊น”๋”ํ•˜๊ฒŒ ๋ฌธ์ œ๋ฅผ ํ’€์ดํ•  ์ˆ˜ ์žˆ๋‹ค.

const rowLen = matrix.length;
const colLen = matrix[0].length;

let curRow = rowLen - 1;
let curCol = 0;โ€‹

์ด๋ฒˆ ํ’€์ด๋Š” ์™ผ์ชฝ ํ•˜๋‹จ ๋๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์˜€๋‹ค. (์˜ค๋ฅธ์ชฝ ์ƒ๋‹จ ๋์€ curRow = 0; curCol = colLen - 1; ๋กœ ๋ฐ”๊พธ๋ฉด ๋จ)

while(curRow >= 0 && curCol < colLen){
    const curVal = matrix[curRow][curCol];

    if(curVal > target){
        curRow--;
    }else if(curVal < target){
        curCol++;
    }else{
        return true;
    }
}

matrix ๋ฒ”์œ„ ๋‚ด์—์„œ
1. target ๊ฐ’์ด ํ˜„์žฌ ๊ฐ’๋ณด๋‹ค ์ž‘์œผ๋ฉด ํ–‰์„ ํ•˜๋‚˜ ์ค„์ธ๋‹ค.

2. target ๊ฐ’์ด ํ˜„์žฌ ๊ฐ’๋ณด๋‹ค ํฌ๋ฉด ์—ด์„ ํ•˜๋‚˜ ํ‚ค์šด๋‹ค.

3. ๊ฐ™์œผ๋ฉด target๊ฐ’์„ ๋ฐœ๊ฒฌํ•˜์˜€์œผ๋ฏ€๋กœ true๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

4. ๋ฒ”์œ„์—์„œ ๋ฒ—์–ด๋‚˜๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target) {
    const rowLen = matrix.length;
    const colLen = matrix[0].length;
    
    let curRow = rowLen - 1;
    let curCol = 0;
    
    while(curRow >= 0 && curCol < colLen){
        const curVal = matrix[curRow][curCol];
        
        if(curVal > target){
            curRow--;
        }else if(curVal < target){
            curCol++;
        }else{
            return true;
        }
    }
    
    return false;
};

'์ฝ”๋”ฉํ…Œ์ŠคํŠธ > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] Valid Anagram  (0) 2022.07.28
[LeetCode] Median Of Two Sorted Arrays  (0) 2022.07.25
[LeetCode] Number Of Matching Subsequences  (0) 2022.07.20
[LeetCode] Pascals Triangle  (0) 2022.07.19
[LeetCode] Single Number II  (0) 2022.07.15