在数组中找到两数之和为 target --

function twoSum2(nums, target) {
  // 查找 hash table
  let obj = {}
  for (let i = 0, len = nums.length; i < len; i++) {
    let item = nums[i]
    let j = target - item
    if (typeof obj[j] !== 'undefined') {
      return [obj[j], i]
    }
    obj[item] = i
  }
  return ''
}

const r = twoSum2([1, 3, 4, 2, 1], 2)
console.log(r)

你可能感兴趣的:(在数组中找到两数之和为 target --)