陣列中和最接近 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