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對應的值所在位置
相關文章
相關標籤/搜索