首页 > 解决方案 > 如何检查数组中任意两个整数的和是否作为数组中的一项存在?

问题描述

我正在编写一个函数,如果数组中任意两个整数的和作为数组中的一项存在,则返回 true。例如:

[3, 4, 8, 11]
//returns true because 8 + 3 = 11 

[2, 4, 7, 12]
//returns false 

到目前为止,我有这个:

const checkArray = (arr) => {
  arr.sort((a, b) => a - b);
  let lhs = 0;
  let rhs = array.length - 1;

  while (lhs < rhs) {
    const sum = arr[lhs] + arr[rhs];

    if (arr.includes(sum)) {
      return true;
    } else if (arr[lhs] < sum) {
      lhs++;
    } else {
      rhs--;
    }
  }
  return true;
}

做了一段时间,不知道我做错了什么。

标签: javascriptarraysalgorithm

解决方案


我尝试不进行排序:

const checkArray = (arr) => {
  if (arr.length < 2) return false;
  let lhs = 0;
  while (lhs < arr.length - 2) {
    let rhs = lhs + 1;
    while (rhs <= arr.length - 1) {
      if (arr.includes(arr[lhs] + arr[rhs])) {
        return true;
      }
      rhs += 1;
    }
    lhs += 1;
  }
  return false;
};

推荐阅读