๋ฌธ์ ๋งํฌ
https://leetcode.com/problems/path-crossing/description/
๋ฌธ์ ํ์ด
์ด ๋ฌธ์ ๋ Set ๊ฐ์ฒด๋ฅผ ์ด์ฉํ๋ฉด ์ฝ๊ฒ ํ ์ ์๋ค. Set ๊ฐ์ฒด๋ ์ผํ ๋ณด๋ฉด Arrayํํ๋ผ๊ณ ์๊ฐ๋ ์ ๋ ์๋๋ฐ HashTable ํํ๋ฅผ ๋๊ณ ์๊ธฐ์ ์๊ฐ๋ณต์ก๋ ์ฐจ์์์ Array๋ณด๋ค ํจ์ฌ ์ข๋ค. ( Set ๊ฐ์ฒด๋ ๋ด๋ถ์ ์ผ๋ก key์ value๊ฐ ๋์ผํ ๊ตฌ์กฐ์ด๋ฉฐ add๋๋ ์์๊ฐ ๋ณด์ฅ๋๋ค ๊ทธ๋ฆฌ๊ณ iterable ํ๊ธฐ์ ์ํํจ์๋ฅผ ์ฐ๊ธฐ์๋ ์ข๋ค ). ํด๋น ๋ฌธ์ ์ ์๊ฐ ๋ณต์ก๋๋ O(n) ์ด๋ค.
/**
* @param {string} path
* @return {boolean}
*/
var isPathCrossing = function (path) {
let position = [0, 0];
let set = new Set();
set.add("0,0");
for (const direction of path) {
if (direction === "N") {
++position[0];
} else if (direction === "S") {
--position[0];
} else if (direction === "E") {
++position[1];
} else if (direction === "W") {
--position[1];
}
let str = position[0] + "," + position[1];
let size = set.size;
set.add(str);
if (size === set.size) {
return true;
}
}
return false;
};
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode[JS] > 350. Intersection of Two Arrays II (0) | 2025.04.16 |
---|---|
LeetCode[JS] > 1913. Maximum Product Difference Between Two Pairs (0) | 2025.04.09 |
LeetCode [JS] > 1128. Number of Equivalent Domino Pairs (0) | 2025.04.07 |
LeetCode [JS] > 859. Buddy strings (0) | 2025.04.05 |
LeetCode [JS] > 2780. Minimum Index of a Valid Split (0) | 2025.04.05 |