sel*_*ted 5 javascript arrays algorithm
给定一个整数数组,返回两个数字的索引,使它们相加达到特定目标。
例子:
给定 nums =
[3, 2, 4],target = 6,因为
nums[1] + nums[2]= 2 + 4 = 6
return [1, 2]。
解决方案
var twoSum = function(nums, target) {
for(let i = 0; i <= nums.length; i++){
for(let j = 0; j <= nums.length; j++){
if(nums[i] + nums[j] == target){
return [i, j]
}
}
}
};
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于其他情况,但不适用于这种情况。
预期结果 [1,2]
输出 [0,0]
例如,我尝试使用不同的数字数组和不同的目标,即使您更改数字的顺序它也能工作
例子:
新数组:[15, 7, 11, 2],目标= 9,
输出: [1, 3]。
我不明白这个解决方案有什么问题,希望有人能解释一下。谢谢
Pra*_*ena 12
您可以使用一种非常简单的技术。
基本上,您可以检查数组中是否存在目标与当前迭代中的元素的差异。
假设相同的索引不能使用两次
nums = [3, 2, 4], target = 6
nums[0] = 3
target = 6
diff = 6 - 3 = 3
nums.indexOf[3] = 0 // FAILURE case because it's the same index
// move to next iteration
nums[1] = 2
target = 6
diff = 6 - 2 = 4
nums.indexOf(4) = 2 // SUCCESS '4' exists in the array nums
// break the loop
Run Code Online (Sandbox Code Playgroud)
这是leetcode接受的答案。
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for (let index = 0; index < nums.length; index++) {
const diff = target - nums[index];
const diffIndex = nums.indexOf(diff);
// "diffIndex !== index" takes care of same index not being reused
if (diffIndex !== -1 && diffIndex !== index) {
return [index, diffIndex];
}
}
};
Run Code Online (Sandbox Code Playgroud)
运行时间:72 ms,比 93.74% 的 JavaScript 在线提交的 Two Sum 更快。
内存使用量:38.5 MB,低于两个 Sum 的 JavaScript 在线提交的 90.55%。
有人可以帮助我减少内存使用吗?
我不明白该解决方案有什么问题,希望有人能解释一下?
在这里,内部循环和外部循环都从0th开始,因此在这种情况下[3,2,4] and target 6 它将返回[0,0]等于3 + 3目标,因此要注意相同的索引元素不被使用两次,从而1在外部循环和内部循环之间创建差异
0使外循环从索引开始,内循环从值开始i+1
var twoSum = function(nums, target) {
for(let i = 0; i < nums.length; i++){
for(let j = i+1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return [i, j]
}
}
}
};
console.log(twoSum([15, 7, 11, 2],9))
console.log(twoSum([3, 2, 4],6))Run Code Online (Sandbox Code Playgroud)