๋ฌธ์ ๋งํฌ
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 |