javascript 二和算法的问题

cqoc49vn  于 2023-06-20  发布在  Java
关注(0)|答案(2)|浏览(131)

谁能告诉我为什么当我调用函数时,我得到了undefined。我可以在函数内部访问结果,但不能在函数外部访问。

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 < 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("No two sum exists");
    } else {
        console.log(arrayOfIndices);
    }
    let result = arrayOfIndices;
    console.log(result);
}

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

ctzwtxfj1#

您需要将return result添加到函数的最后一行。它没有返回任何东西。

kokeuurv

kokeuurv2#

这看起来像一个LeetCode问题(Two Sum)。时间复杂度为O(n^2)。它也不会短路(提前返回),所以你正在计算数组中每个数字的总和。
正如其他人已经提到的,你需要在你的函数中返回索引数组。你没有那么做。我没有看到return arrayOfIndices,也没有看到return result
只需将余数存储在一个Map中,其中所需的值(compliment)是您尚未遇到的值。一旦你得到了赞美,返回它的索引;沿着所存储的余数的索引。

/**
 * 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) => {
  let remainderMap = new Map();
  for (let i = 0; i < nums.length; i++) {
    let diff = target - nums[i]; // complement -> 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}`);

相关问题