数组元素(相邻)对,其和为最低值 JavaScript
我们需要编写一个 JavaScript 函数,它接受一个数字数组。该函数应从原始数组中返回一个由两个相邻元素组成的子数组,其和在数组中的所有相邻对中最小。
如果数组长度小于 2,我们应该返回布尔值 false。
例如,如果输入数组是 −
const arr = [41, 44, -12, 13, -23, 1, 5, -4, 2, 2];
此处,对 [-23, 1] 的和为 -22,这是数组中任意两个相邻元素的最小值,因此该函数应返回 [-23, 1]
代码如下 −
const arr = [41, 44, -12, 13, -23, 1, 5, -4, 2, 2];
const leastSum = arr => {
if(arr.length <= 2){
return false;
};
const creds = arr.reduce((acc, val, ind) => {
let { smallest, startIndex } = acc;
const next = arr[ind+1] ;
if(!next){
return acc;
}
const sum = val + next;
if(sum < smallest){
startIndex = ind;
smallest = sum;
};
return { startIndex, smallest };
}, {
smallest: Infinity,
startIndex: -1
});
const { startIndex } = creds;
return [arr[startIndex], arr[startIndex + 1]];
};
console.log(leastSum(arr));以下是在控制台上的输出 −
[-23, 1]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP