两数之和算法问题

huangapple go评论93阅读模式
英文:

Issue with two sum algorithm

问题

当我调用这个函数时,为什么会得到未定义的结果?我可以在函数内部访问结果,但在外部却不能。

function twoSum(nums, target) {
    console.log(nums); // 跟踪用户输入。
    console.log(target); // 跟踪目标值。

    let arrayOfIndices = [];

    // 遍历数组并执行加法操作
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                arrayOfIndices.push([i, j]);
            }
        }
    }

    if (arrayOfIndices.length === 0) {
        console.log("找不到两个数的和等于目标值");
    } else {
        console.log(arrayOfIndices);
    }
    let result = arrayOfIndices;
    console.log(result);
}

// 测试用例
console.log(twoSum([3, 4, 5], 7));
英文:

Can anyone tell me why when I call the function, I'm getting undefined. I can access the result inside of the function but not outside.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function twoSum(nums, target) {
    console.log(nums); // keep track of user input.
    console.log(target); // keep track of target.

    let arrayOfIndices = [];

    // loop through array and perform addition operation
    for (let i = 0; i &lt; nums.length; i++) {
        for (let j = i + 1; j &lt; nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                arrayOfIndices.push([i, j]);
            }
        }
    }

    if (arrayOfIndices.length === 0) {
        console.log(&quot;No two sum exists&quot;);
    } else {
        console.log(arrayOfIndices);
    }
    let result = arrayOfIndices;
    console.log(result);
}

// Test case
console.log(twoSum([3, 4, 5], 7));

<!-- end snippet -->

答案1

得分: 1

你需要将return result添加到你的函数最后一行。它没有返回任何内容。

英文:

You need to add return result to the last line of your function. It's not returning anything.

答案2

得分: 0

这看起来像是一个LeetCode问题(Two Sum)。你因为你的算法需要O(n^2)的时间而使它变得过于复杂。它也没有提前终止(早期返回),所以你在计算数组中每个数字的所有和。

正如其他人已经提到的,你需要在你的函数中返回索引数组。你没有这样做。我在那个函数中看不到return arrayOfIndices,也看不到return result

只需将余数存储在一个映射中,其中所需值(补数)是你尚未遇到的值。一旦你得到了补数,就返回它的索引;以及存储的余数的索引。

/**
 * 给定一个整数数组 nums 和一个整数目标值 target,返回两个数字的索引,
 * 这两个数字相加等于目标值。
 * @param {number[]} nums - 整数数组
 * @param {number} target - 目标和
 * @return {number[]} 使得和等于目标值的两个数字的索引。
 */
const twoSum = (nums, target) => {
  let remainderMap = new Map();
  for (let i = 0; i < nums.length; i++) {
    let diff = target - nums[i]; // 补数 -> 索引
    if (remainderMap.has(diff)) {
      return [i, remainderMap.get(diff)]; // 早期返回
    }
    remainderMap.set(nums[i], i);
  }
};

const
  arr = [3, 4, 5],
  target = 7,
  indices = twoSum(arr, target);
  
console.log(`${arr[indices[0]]} + ${arr[indices[1]]} = ${target}`);
英文:

This looks like a LeetCode problem (Two Sum). You over-complicating this because your algorithm is taking O(n^2) time. It also does not short-circuit (early return), so you are computing all the sums for every number in the array.

As others have already mentioned, you will need to return the array of indices in your function. You did not do that. I do not see return arrayOfIndices nor do I see return result anywhere in that function.

Just store the remainder in a map where the needed value (compliment) is a value you have yet to encounter. Once you have the compliment, return it's index; along with the stored remainder's index.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

/**
 * Given an array of integers nums and an integer target, return indices
 * of the two numbers such that they add up to target.
 * @param {number[]} nums - array of integers
 * @param {number} target - target sum
 * @return {number[]} indices of the two numbers where sum is the target.
 */
 const twoSum = (nums, target) =&gt; {
  let remainderMap = new Map();
  for (let i = 0; i &lt; nums.length; i++) {
    let diff = target - nums[i]; // complement -&gt; index
    if (remainderMap.has(diff)) {
      return [i, remainderMap.get(diff)]; // Return early
    }
    remainderMap.set(nums[i], i);
  }
};

const
  arr = [3, 4, 5],
  target = 7,
  indices = twoSum(arr, target);
  
console.log(`${arr[indices[0]]} + ${arr[indices[1]]} = ${target}`);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月19日 17:53:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定