陣列元素(相鄰)對,其和為最低值 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