1.js
/** ------------------------------------------------------------------------------
*
* 1. Two Sum
* Topics: Hash Table
* https://leetcode.com/problems/two-sum/description/
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
let hash = {}
for (let i = 0; i < nums.length; i++) {
const n = nums[i]
const diff = target - n
if (diff in hash) {
// if (hash[diff] !== undefined) {
return [hash[target - n], i]
}
hash[n] = i
}
return []
}
console.log(twoSum([2, 7, 11, 15], 9))
/** ------------------------------------------------------------------------------
*
* use Map
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSumMap = function (nums, target) {
const map = new Map()
for (let i = 0; i < nums.length; i++) {
let complement = target - nums[i]
if (map.has(complement)) return [map.get(complement), i]
map.set(nums[i], i)
}
}
console.log(twoSumMap([2, 7, 11, 15], 9))