法一
var twoSums = function (nums, target) {
let hash = {}
let ans = []
for (let i = 0; i < nums.length; i++) {
let temp = target - nums[i]
if (hash[temp] !== undefined) {
ans.push(hash[temp])
ans.push(i)
return ans
} else {
hash[nums[i]] = i
}
}
return ans
}
let wk = [1, 2, 3, 4, 5, 6, 7, 8]
let target = 12
console.log(twoSums(wk, target))
- 打比方,找对象,主办方拿个本子,你需要什么样的对象,你一来就告诉主办⽅,然后看本子里有没有匹配的,有就直接牵手,没有就登记自己需要找的对象是什么标准
var twoSum = function (nums, target) {
let obj = {};
for (let i = 0; i < nums.length; i++) {
let num = nums[i];
let expect = target - num;
if (num in obj) {
return [obj[num], i];
} else {
obj[expect] = i;
}
}
};
var twoSum = function (nums, target) {
var 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("No two sum solution");
};
法二
var twoSums = function (nums, target) {
const len = nums.length
while (true) {
const i = parseInt(Math.random() * len)
const j = parseInt(Math.random() * len)
if (i !== j && nums[i] + nums[j] == target) {
return [i, j]
}
}
}
let wk = [1, 2, 3, 4, 5, 6, 7, 8]
let target = 12
console.log(twoSums(wk, target))