数组中和最接近 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]

更新时间:16-9-2020

117 次浏览

开始你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.