diff --git a/contains-duplicate/Cyjin-jani.js b/contains-duplicate/Cyjin-jani.js new file mode 100644 index 0000000000..304b042b68 --- /dev/null +++ b/contains-duplicate/Cyjin-jani.js @@ -0,0 +1,4 @@ +const containsDuplicate = function (nums) { + const data = new Set(nums); + return data.size !== nums.length; +}; diff --git a/house-robber/Cyjin-jani.js b/house-robber/Cyjin-jani.js new file mode 100644 index 0000000000..53270e3b76 --- /dev/null +++ b/house-robber/Cyjin-jani.js @@ -0,0 +1,11 @@ +const rob = function (nums) { + // 최대 누적값을 저장하는 배열 + const data = []; + data[0] = nums[0]; + + for (let i = 1; i < nums.length; i++) { + data[i] = Math.max(data[i - 1], (data[i - 2] ?? 0) + nums[i]); + } + + return data[data.length - 1]; +}; diff --git a/longest-consecutive-sequence/Cyjin-jani.js b/longest-consecutive-sequence/Cyjin-jani.js new file mode 100644 index 0000000000..fc730e379f --- /dev/null +++ b/longest-consecutive-sequence/Cyjin-jani.js @@ -0,0 +1,22 @@ +var longestConsecutive = function (nums) { + // 숫자 존재 유무를 확인할 수 있는 자료구조 세팅 + const dataSet = new Set(nums); + let answer = 0; + + // 전체 숫자를 순회하면서 시작점을 확인 + for (let num of dataSet) { + // num - 1이 dataSet에 있는지 확인. 있다면 시작점이 아니므로 패스 + if (!dataSet.has(num - 1)) { + // 없다면 시작점. 여기서부터 연속된 숫자가 얼마나 있는지 카운팅. + let count = 1; + let target = num; + while (dataSet.has(target + 1)) { + count++; + target++; + } + // longest를 구하는 문제이므로 max로 더 긴 답을 판단 + answer = Math.max(count, answer); + } + } + return answer; +}; diff --git a/top-k-frequent-elements/Cyjin-jani.js b/top-k-frequent-elements/Cyjin-jani.js new file mode 100644 index 0000000000..7c1a2d8813 --- /dev/null +++ b/top-k-frequent-elements/Cyjin-jani.js @@ -0,0 +1,23 @@ +const topKFrequent = function (nums, k) { + const tempArr = Array.from({ length: nums.length }, () => []); + const obj = {}; + + for (let num of nums) { + obj[num] = (obj[num] || 0) + 1; + } + + for (let key in obj) { + const val = obj[key] - 1; + tempArr[val].push(+key); + } + + // answer.flat(), return answer.slice(-k) 대신 좀 더 최적화된 코드로 변경합니다. + const answer = []; + for (let i = tempArr.length - 1; i >= 0; i--) { + for (let num of tempArr[i]) { + answer.push(num); + if (answer.length === k) return answer; + } + } + return answer; +}; diff --git a/two-sum/Cyjin-jani.js b/two-sum/Cyjin-jani.js new file mode 100644 index 0000000000..a450ae29d8 --- /dev/null +++ b/two-sum/Cyjin-jani.js @@ -0,0 +1,14 @@ +const twoSum = function (nums, target) { + let memo = {}; + + for (let i = 0; i < nums.length; i++) { + let current = nums[i]; + let needed = target - current; + + if (needed in memo) { + return [memo[needed], i]; + } + + memo[current] = i; + } +};