1. Two Sum
利用给出的提示,每个target仅有一个解(exactly one solution)
加上利用hashtable存储已经遍历的值
简单解题思路:
1.设置存储键值对的storeMap value:index
2.如果存在符合条件的值即 storeMap[target - n] === 'number',直接返回 [storedIndex, i],否则存储已经遍历的值 storeMap[val] = i
3.循环以上步骤,如果没有就返回空数组 []
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
// only one result match
const twoSum = function(nums, target) {
const storeMap = {}
for(let i = 0; i < nums.length;i++) {
let val = nums[i]
let storedIndex = storeMap[target - val]
let isValid = typeof storedIndex === 'number'
if(isValid) {
return [storedIndex, i]
} else {
storeMap[val] = i
}
}
return []
};