Two Sum

@paddingme 2018-08-23 14:48:48发表于 paddingme/shipping Algorithms

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].

Solution

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    for (let i = 0 ; i < nums.length; i++) {
        let s = nums.findIndex((e, index) => {
            if (e === (target - nums[i])) {
                if (i === index) return false
                return true
            }
            return false
        })
        if (s > -1) return [i, s]
    }
    return []
}
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let obj = {}
    nums.map((num, index) => (obj[num] = index))
    for (let i = 0; i < nums.length; i++) {
        let second = target - nums[i]
        if (obj.hasOwnProperty(second) && (obj[second] !== i)) {
            return [i ,obj[second]]
        }
    }
    return []
}
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  let obj = {}
  for (let i = 0; i < nums.length; i++) {
    let num = nums[i]
    let second = target - num
    if (obj.hasOwnProperty(second)) {
      return [obj[second], i]
    }
    obj[num] = i
  }
  return []
}