diff --git a/ Contains Duplicate.js b/ContainsDuplicate.js similarity index 80% rename from Contains Duplicate.js rename to ContainsDuplicate.js index 1121971..184d33c 100644 --- a/ Contains Duplicate.js +++ b/ContainsDuplicate.js @@ -13,3 +13,5 @@ const containsDuplicate = function (nums) { return newArr.some((x) => x >= 2); }; + +// https://leetcode.com/problems/contains-duplicate/description/ diff --git a/LongestConsecutiveSequence.js b/LongestConsecutiveSequence.js new file mode 100644 index 0000000..258ba4a --- /dev/null +++ b/LongestConsecutiveSequence.js @@ -0,0 +1,29 @@ +// Given an unsorted array of integers nums, +// return the length of the longest consecutive elements sequence. +// You must write an algorithm that runs in O(n) time. + +const longestConsecutive = (nums) => { + if (!nums.length) return 0; + + const x = [...new Set(nums)].sort((a, b) => a - b); + const answer = []; + + let cnt = 1; + + x.forEach((v, i) => { + if (v + 1 === x[i + 1]) { + cnt += 1; + } else { + answer.push(cnt); + cnt = 1; + } + }); + + return Math.max(...answer); +}; + +const nums = [1, 2, 0, 1]; +const x = longestConsecutive(nums); +console.log(x); + +// https://leetcode.com/problems/longest-consecutive-sequence/description/ diff --git a/TwoSum.js b/TwoSum.js index 27013e2..0866bf3 100644 --- a/TwoSum.js +++ b/TwoSum.js @@ -20,3 +20,5 @@ const nums = [3, 2, 3]; const target = 6; const a = twoSum(nums, target); console.log(a); + +// https://leetcode.com/problems/two-sum/description/ diff --git a/topKFrequent.js b/topKFrequent.js new file mode 100644 index 0000000..532f7a1 --- /dev/null +++ b/topKFrequent.js @@ -0,0 +1,27 @@ +// Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. + +const topKFrequent = (nums, k) => { + const obj = {}; + + for (let i = 0; i < nums.length; i++) { + const v = nums[i]; + if (obj[v]) { + obj[v] += 1; + } else { + obj[v] = 1; + } + } + + const sortedArray = Object.entries(obj).sort((a, b) => b[1] - a[1]); + const answer = sortedArray.slice(0, k).map(([num, _]) => Number(num)); + return answer; + + //[ [ '1', 3 ], [ '2', 2 ], [ '3', 3 ] ] + // 0:숫자 1:몇개가 존재하는지 + // [1] 번째 인덱스 () 순서대로 정렬. +}; + +const nums = [1, 1, 1, 2, 2, 3, 3, 3]; + +const k = 2; +const a = topKFrequent(nums, k);