seanhuai
3/29/2018 - 10:26 AM

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 wo

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.

// 哈希表解法
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  let length = nums.length,
    hash = {},
    x,y,index = 0;
  while(index < length){
    x = nums[index];
    y = hash[x];
    if(y!==undefined){
      return [y,index];
    }else{
      hash[target-x] = index; 
    }
    index++;
  }
};

// 遍历解法
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    for(let i = 0; i<nums.length; i++){
        for(let x = i+1; x<nums.length; x++){
            if(nums[i]+nums[x] == target) {
                return [i,x]
            }
        }
    }
};