Leetcode 1 两数之和

问题描述

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

实例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解决方法

解法一

暴力遍历方法,通过双层遍历,穷尽组合找到两个元素,使之和满足目标值。

原理:双层遍历所有元素,找到 a + b = target 的元素的索引。

时间复杂度为 O(n^2),空间复杂度为 O(1)。

var twoSum = function(nums, target) {

  for (let i = 0; i < nums.length; i++) {
    const a = nums[i];
    
    for (let j = i + 1; i < nums.length; i++) {
      const b = nums[i];
      if (a + b === target) {
        return [i, j];
      }
    }
  }

  return new Error('there is no answer');
};

解法二

为了快速的查找 target - nums[i] 元素所在的位置,我们可以使用哈希表快速查找元素。比起遍历算法,执行的时间效率为 O(1)。具体实现如下:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  const map = new Map();

  nums.forEach((value, index) => {
    map.set(value, index);
  });

  for (let i = 0; i < nums.length; i++) {
    const a = nums[i];
    const residual_value = target - a;
    const j = map.get(residual_value);
    if (j !== undefined && j !== i) {
      return [i, j];
    }
  }

  return new Error('there is no answer');
};

时间复杂度为 O(n),空间复杂度为 O(n)。

解法三

仍然是使用哈希表找元素,但是只使用一次哈希。

var twoSum = function(nums, target) {

  const map = new Map();

  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];

    if (map.get(complement)) {
      return [map.get(complement), i];
    }
    
    map.set(nums[i], i);
  }

  return new Error('there is no answer');
};

参考文档

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目: 题目地址:https://leetcode-cn.com/problems/two-sum/ 问题描述: ...
    MrGeekr极氪阅读 640评论 0 0
  • 两数之和 LeetCode 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和...
    天空像天空一样蓝阅读 262评论 0 2
  • 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并...
    Chase_Eleven阅读 336评论 2 0
  • LeetCode:1两数之和 标签:数组、哈希表 给定一个整数数组 nums 和一个目标值 target,请你在该...
    burger8阅读 117评论 0 0
  • 山河是 城市的母亲 人是城市 弑母的凶器 没有罪咎 没有恩情 别太高看自己 凶器保持中立
    一枝小草阅读 129评论 0 0