两数之和
链接: 力扣链接
什么时候使用哈希法
- 当我们需要查询一个元素是否出现过
- 或者一个元素是否在集合里的时候,就要第一时间想到哈希法
常见的三种哈希结构
当我们想使用哈希法来解决问题的时候,我们一般会选择如下三种数据结构。
- 数组
- set (集合)
- map(映射)
var twoSum = function (nums, target) {
let hash = {};
for (let i = 0; i < nums.length; i++) {
if (hash[target - nums[i]] !== undefined) {
return [ hash[target - nums[i]],i];
}
hash[nums[i]] = i;
}
return [];
};
console.log('twoSum([2,7,6,7],9): ', twoSum([2, 7, 6, 7], 9));
//my
function twoSum(nums, target) {
const indexList = [];
for (let i = 0; i < nums .length; i++) {
const ele = nums[i];
let temp = target - ele;
if (nums.includes(temp)) {
const findIndex = nums.lastIndexOf(temp)
if (i !== findIndex) {
indexList.push(i);
indexList.push(findIndex);
break
}
}
}
return indexList;
}
twoSum([2,7,6,7],9)