diff --git a/doitchuu/BinarySearch.js b/doitchuu/BinarySearch.js new file mode 100644 index 0000000..c9329d9 --- /dev/null +++ b/doitchuu/BinarySearch.js @@ -0,0 +1,27 @@ +function search(nums, target) { + return nums.indexOf(target); +} + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { + let start = 0; + let end = nums.length - 1; + + while (start <= end) { + const middle = Math.floor((start + end) / 2); + + if (nums[middle] === target) { + return middle; + } else if (nums[middle] > target) { + end = middle - 1; + } else { + start = middle + 1; + } + } + + return -1; +}; diff --git a/doitchuu/FloodFill.js b/doitchuu/FloodFill.js new file mode 100644 index 0000000..2f5123f --- /dev/null +++ b/doitchuu/FloodFill.js @@ -0,0 +1,30 @@ +var floodFill = function (image, sr, sc, color) { + const dx = [-1, 0, 1, 0]; + const dy = [0, 1, 0, -1]; + + const original = image[sr][sc]; + if (original === color) return image; + + const rows = image.length; + const cols = image[0].length; + + const queue = [[sr, sc]]; + image[sr][sc] = color; // 방문 처리(색칠) 먼저 + + while (queue.length) { + const [x, y] = queue.shift(); + + for (let dir = 0; dir < 4; dir++) { + const nx = x + dx[dir]; + const ny = y + dy[dir]; + + if (nx < 0 || ny < 0 || nx >= rows || ny >= cols) continue; + if (image[nx][ny] !== original) continue; + + image[nx][ny] = color; + queue.push([nx, ny]); + } + } + + return image; +}; diff --git a/doitchuu/InvertBinaryTree.js b/doitchuu/InvertBinaryTree.js new file mode 100644 index 0000000..92fc411 --- /dev/null +++ b/doitchuu/InvertBinaryTree.js @@ -0,0 +1,12 @@ +function invertTree(root) { + if (root === null) return null; + + const temp = root.left; + root.left = root.right; + root.right = temp; + + invertTree(root.left); + invertTree(root.right); + + return root; +} diff --git a/doitchuu/ValidAnagram.js b/doitchuu/ValidAnagram.js new file mode 100644 index 0000000..d320589 --- /dev/null +++ b/doitchuu/ValidAnagram.js @@ -0,0 +1,32 @@ +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = function (s, t) { + if (s.length !== t.length) { + return false; + } + + const sMap = new Map(); + const tMap = new Map(); + + for (let i = 0; i < s.length; i++) { + sMap.set(s[i], (sMap.get(s[i]) ?? 0) + 1); + tMap.set(t[i], (tMap.get(t[i]) ?? 0) + 1); + } + + for (const [key, value] of sMap) { + const tValue = tMap.get(key); + + if (tValue === undefined) { + return false; + } + + if (tValue !== value) { + return false; + } + } + + return true; +};