数组中和最接近 0 的相邻元素 - JavaScript
我们需要编写一个 JavaScript 函数,该函数接受一个数字数组并从原始数组中返回一个长度为 2 的子数组,其和最接近 0。
如果数组的长度小于 2,则应返回整个数组。
例如:如果输入数组是 −
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
这里,对 [5, -4] 的求和是 1,这是数组的任意两个相邻元素最接近 0 的值,因此我们应该返回 [5, -4]
范例
以下是代码 −
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
const closestElements = (arr, sum) => {
if(arr.length <= 2){
return arr;
}
const creds = arr.reduce((acc, val, ind) => {
let { closest, startIndex } = acc;
const next = arr[ind+1];
if(!next){
return acc;
}
const diff = Math.abs(sum - (val + next));
if(diff < closest){
startIndex = ind;
closest = diff;
};
return { startIndex, closest };
}, {
closest: Infinity,
startIndex: -1
});
const { startIndex: s } = creds;
return [arr[s], arr[s+1]];
};
console.log(closestElements(arr, 1));输出
以下是控制台中的输出 −
[5, -4]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP