数组中相邻元素对的和最小 JavaScript

javascriptweb developmentobject oriented programmingfront end technology更新于 2026/1/16 21:00:17

我们需要编写一个 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]

相关文章


有用资源