原题描述:
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].
题目意思
从数组中找出A+B=C,返回A和B在数组中的位置,数组中一定存在A和B相加等于C,并且A和B不能相等
- 解法
var twoSum = function(array, target) {
const len = array.length;
// 因为肯定有解,且值不一样,所以数组只有两个值的时候这两个值就为解
if (len === 2) return [0, 1];
let obj = {};
for(let i = 0; i < len; i++) {
let value = target - array[i];
//value in obj判断obj对象是否有一个key为value
if(value in obj ) return [obj[value], i];
//obj对象的key是原来数组的值,value是该值的位置
else obj[arrays[i]] = i;
}
};
其实思路就是:
array = [6,9,10,12],target = 15
obj = {6:0, 9:1, 10:2, 12:3}
15 = 6 + 9 = array[0] + obj[9]
网友评论