Skip to content

Latest commit

 

History

History
31 lines (26 loc) · 828 Bytes

1.md

File metadata and controls

31 lines (26 loc) · 828 Bytes

Leetcode 1. 两数之和

1. 两数之和

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
  // 用于存储未匹配数字
  let unmatched = {};
  unmatched[nums[0]] = 0;

  // 遍历数组
  for (let i = 1; i < nums.length; i++) {
    let difference = target - nums[i]; // 两数之差,当前数字 nums[i] 需要的配对数字
    // 查找 difference 在 unmatched 中是否存在
    // 如果存在,直接返回 difference 所在的下标以及当前数字的下标
    // 如果不存在,则将当前数字以及下标写入临时数组中
    if (unmatched.hasOwnProperty(difference)) {
      return [unmatched[difference], i];
    } else {
      unmatched[nums[i]] = i;
    }
  }
};