题目地址:链接
题目描述: 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。你可以按任意顺序返回答案。
题目概述: 找到两个和为target的下标。
示例输出:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
暴力枚举
var twoSum = function(nums, target) {
let n = nums.length;
for(let i = 0; i < n; i ++) {
for(let j = i + 1; j < n; j ++) {
if (nums[i] + nums[j] == target) {
return [i, j];
}
}
}
};
哈希表
var twoSum = function(nums, target) {
let hash = {}
let n = nums.length;
for(let [i, num] of nums.entries()) {
if (hash[target - num] !== undefined) {
return [hash[target - num], i]
}
hash[num] = i
}
};
8万+

被折叠的 条评论
为什么被折叠?



