leetcode001两数之和

83 阅读1分钟

1. 两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。

你可以按任意顺序返回答案。

输入: nums = [2,7,11,15], target = 9 输出: [0,1] 解释: 因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

暴力解答: 两层遍历 时间复杂度 O(n*n)

let twoSum = function (nums, target) {
  let res = []
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] === target) {
        res[0] = i
        res[1] = j
      }
    }
  }
  return res
}

但是除了应试之外个人觉得暴力解法意义不大

下面借用hash实现一个时间复杂度为 O(n)的写法

var twoSum = function (nums, target) {
  let hashMap = new Map()
  let len = nums.length
  for (let i = 0; i < len; i++) {
    if (hashMap.has(target - nums[i])) {
      return [i, hashMap.get(target - nums[i])]
    }
    hashMap.set(nums[i], i)
  }
};

一次遍历,判断target-num[i]的值是否已经在hash表中存在,查找到则返回两者下标,没找到的话则将nums[i]i 存入hash表中