javascript - 如何检查数组中任意两个整数的和是否作为数组中的一项存在?
问题描述
我正在编写一个函数,如果数组中任意两个整数的和作为数组中的一项存在,则返回 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;
}
做了一段时间,不知道我做错了什么。
解决方案
我尝试不进行排序:
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;
};
推荐阅读
- laravel - Laravel Spark:如何选择试用提供的计划?
- javascript - 通过 Safari 上的 onclick 事件播放音频
- c# - WPF .Net Core 3.0 中的路径
- r - 用 R 中的新日期替换日期列的 NA
- powerbuilder - 有什么办法可以在 PowerBuilder 中处理 JSON?
- python - Python:如何将日期列表转换为会议日期列表
- excel - 为什么宏给出编译错误而脚本中没有任何逻辑或语法错误?
- c# - 问题,OnCollisionStay 上的布尔冲突
- c++ - 大向量和内存保护c ++
- firefox - 是否需要在嵌套 CSS 网格中的每个级别指定“子网格”?