leetcode-Easy-第1期:two sum

原题描述:

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.
题目意思
从数组中找出A+B=C, 返回A和B在数组中的 位置,数组中必定存在A和B相加等于C,而且A和B不能相等
  • Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
  • 解法
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 //而后返回6和9对应的值所在位置
相关文章
相关标签/搜索