diff --git a/source/_posts/twoSum.md b/source/_posts/twoSum.md index 863a1bf..bde01f5 100644 --- a/source/_posts/twoSum.md +++ b/source/_posts/twoSum.md @@ -7,4 +7,67 @@ categories: - LeetCode description: LeetCode twoSum题 cover: https://upload.wikimedia.org/wikipedia/commons/0/0a/LeetCode_Logo_black_with_text.svg ---- \ No newline at end of file +--- +Given an array of integers, return indices of the two numbers such that they add up to a specific target. + +You may assume that each input would have exactly one solution, and you may not use the same element twice. + +Example: + +Given nums = [2, 7, 11, 15], target = 9, + +Because nums[0] + nums[1] = 2 + 7 = 9, +return [0, 1]. + +```javascript +nums = [2, 7, 11, 15]; +console.log(nums); + +total = nums[0] + nums[1]; +console.log(total); + +const twoSum = function (nums, target) { + const totals = {}; + for (let i = 0; i < nums.length; i++) { + if (total[nums[i]] >= 0) { + return [total[nums[i]], i]; + } + } +}; +``` +```javascript +const twoSum = function (nums, target) { + const comp = {}; + for (let i = 0; i < nums.length; i++) { + if (comp[nums[i]] >= 0) { + return [comp[nums[i]], i] + } + comp[target - nums[i]] = i; + } +}; +``` +```javascript +// O(n) - One-pass Hash Table +let twoSum = function (nums, target) { + let map = new Map; + for (let i = 0; i < nums.length; i++) { + let completement = target - nums[i]; + if (map.has(complement)) { + return [map.get(complement), i] + } + map.set(nums[i], i); + } +} +``` +```javascript +const twoSum = function (nums, target) { + const map = new Map(); + for (let i = 0; i < nums.length; i++) { + const comp = target - nums[i]; + if (map.has(comp)) { + return [map.get(comp), i]; + } + map.set(nums[i], i); + } +}; +``` \ No newline at end of file