题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
JavaScript实现
方法一:暴力解法
使用2个嵌套for循环实现,外层for循环从索引 i 开始,内层for循环索引从 i+1 开始,找到数组中存在两个元素之和等于目标元素时,把内外2层for循环中的索引值存放到数组中放回。具体实现代码如下所示:
/**
* @param {number[]} nums 整数数组
* @param {number} target 目标值
* @return [number[]] 返回一个数组
* 时间复杂度为 O(n^2)
*/
function twoSum(nums, target)
{
if(nums.length < 2) return [];
let len = nums.length;
for (let i = 0; i < len; ++i)
{
for (let j = i + 1; j < len; ++j)
{
if (nums[i] + nums[j] == target)
return [i, j];
}
}
return [];
}
方法二:使用Map方法
具体解题思路:
- 声明一个空数组(用于模拟Map)或者Map类型的变量 mapValue,以 kev-value 的形式存放数组中的元素值和对应的索引;
- 使用 for 循环遍历数组,如果 target - nums[i] 的值不存在与 mapValue 中,则把 nums[i] 存放到 mapValue 中;如果存在,则返回对应的索引组成的数组。
使用数据模拟map,具体代码实现如下所示:
/**
* @param {number[]} nums 整数数组
* @param {number} target 目标值
* @return [number[]] 返回一个数组
*/
function twoSum(nums, target)
{
if (nums.length < 2) return [];
let mapValue = [];
let len = nums.length;
for (let i = 0; i < len; ++i)
{
let subValue = target - nums[i];
if (mapValue[subValue] != undefined)
return [mapValue[subValue], i];
mapValue[nums[i]] = i; // 容易消耗不必要的存储,比如 [undefined, undefined, 4...]
}
return [];
}
使用Map类型变量的具体实现代码如下所示:
/**
* @param {number[]} nums 整数数组
* @param {number} target 目标值
* @return [number[]] 返回一个数组
*/
function twoSum(nums, target)
{
if (nums.length < 2) return [];
let mapValue = new Map();
let len = nums.length;
for (let i = 0; i < len; ++i)
{
let subValue = target - nums[i];
if (mapValue.has(subValue))
return [mapValue.get(subValue), i];
mapValue.set(nums[i], i);
}
return [];
}