【问题标题】:A function that finds two numbers out of an array that add up to the given number从数组中找出两个数相加等于给定数的函数
【发布时间】:2020-11-20 09:07:46
【问题描述】:

我目前正在尝试创建一个从随机数组中查找两个数字并找出哪两个加起来等于给定数字的函数。它只需要告诉我这两个数字在什么索引上。 我最好的尝试如下,但我无法解决:

function numbers([N], sum) {
  x = 0;
  y = N.length - 1;
  while (x < y) {
    if (N[x] + N[y] == sum)
      return true;
    else if (N[x] + N[y] < sum)
      x++;
    return false
  }

console.log(numbers([5, 2, 1, 9, 15], 6))

所以如果我在这里记录最后一位,我希望它给我索引 0 和 2,因为它们加起来是 6。 希望这是有道理的。我是编码新手,并且已经用谷歌搜索了其中的大部分内容。 提前致谢

【问题讨论】:

  • 你确定要解构数组[N]以获取第一项吗?
  • 如果匹配条件的数字不止一对(例如[5,2,1,9,15,4])或数组中有重复数字(例如[5,2,1,9,15,1])怎么办?
  • 是的,你需要 numbers(N, sum)N 最终会是 5,而不是整个数组。我也不确定你的else if;这两个数字的总和为sum,或者不是;这里不需要else ifs。您也没有测试每一对;您必须使用两个嵌套的 for 循环来遍历两个数字的每个可能配对。
  • 您的代码肯定也达到了返回值之一,因此只进行了一次测试,然后函数退出。看看奇怪的缩进,return false 不受else if 测试。

标签: javascript arrays function add


【解决方案1】:

这将返回与总和相加的索引,如果找不到,它将返回 undefined。

function numbers(N, sum) {
    indexes = {};

    for(let i = 0; i < N.length; i++){
        let diff = sum - N[i];

        if(indexes[diff] != undefined && indexes[diff] != i){
            return [i, indexes[diff]];
        }else{
            indexes[N[i]] = i;
        }
    }
}

这种情况将返回 2 和 0。

console.log(numbers([5, 2, 1, 9, 15], 6));
[2, 0]

【讨论】:

  • 如何让它返回 [0,2] 呢?所以它的另一个顺序
  • 这段代码总是会返回前两个数字的索引,但如果数组包含两个以上的和为 6 的数字怎么办?例如,尝试console.log(numbers([5, 2, 1, 9, 15, 4, 5], 6));:该函数仅返回[0, 2],而索引[1, 5][2, 6] 也是有效结果。
【解决方案2】:

当有几对附录给出所需结果并且数字数组包含重复值时,这也应该有效:

const nums = [5, 2, 1, 9, 15, 4, 5];

function removeDuplicateItems(arr) {
  const stringifiedItemsArr = arr.map(item => JSON.stringify(item));
  const uniqueStringifiedItemsSet = new Set(stringifiedItemsArr);
  return Array.from(uniqueStringifiedItemsSet, JSON.parse);
}

function findAddendaIndexes(numArr, sum) {
  const addendaArr = numArr.reduce((addenda, num, index) => {
    const indexB = numArr.findIndex(item => item + num === sum);
    if (indexB !== -1 && indexB !== index) {
      addenda.push([index, indexB].sort((a, b) => a - b));
    }

    return addenda;
  }, []);

  return addendaArr.length > 0 ? removeDuplicateItems(addendaArr).sort((a, b) => a[0] - b[0]) : null;
}

// test
console.log('numbers:', nums);
console.log('sum 6:', findAddendaIndexes(nums, 6));
console.log('sum 8:', findAddendaIndexes(nums, 8));
console.log('sum 10:', findAddendaIndexes(nums, 10));

【讨论】:

    【解决方案3】:

    试试这样:

    function numbers(N, sum) {
      let x, y;
      
      for(let y=0;y<N.length;y++) {
        x = 0;
        
        while (x < y) {
          if (N[x] + N[y] == sum) {
            console.log(x, y); //result
            return true;
          } else {
            x++;
          };
        }
      };
      return false;
    }
    
     console.log(numbers([5, 2, 1, 9, 15], 6));

    如果找到第一个匹配项,上面的代码将返回。 x 索引需要与其他索引 (y) 进行检查,而不仅仅是最后一个索引。已添加 for 循环以遍历可能的 y 索引。

    【讨论】:

    • 当您想要获取的是数组中的索引时,我不确定更改数组项的顺序(通过对它们进行排序)是否有意义。例如,如果您尝试console.log(numbers([15, 2, 1, 9, 5], 6));,它将返回0, 2,但数组的第一个元素 (15) 和第三个元素 (1) 的总和是 16,而不是 6。
    • 好点!它碰巧在那个特定的情况下起作用,所以我没有意识到。我已更新此答案以排除该优化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2015-07-07
    相关资源
    最近更新 更多