如果有一个数组
让 arr = [7,1,4,3,8]
,结果应该是 3,这是 4 和 7 之间的最大差值。
同样,对于 let arr2 = [5,5,5,7,4]
,输出为 2(介于 5 和 7 之间),对于 let arr3 = [6,3, 2,5,9]
是 3(介于 6 和 9 之间)。
找出最大差异的最佳优化解决方案是什么。
我的方法是对数组进行排序并找出连续元素之间的差异,然后使用 Math.max(...differenceValues)
找到最大值
PS:我不是在寻找数组中最大值和最小值之间的差异。当您在 x 轴上绘制图形时,上述问题很有意义。
最佳答案
这是一个使用 reduce 的例子:
let arr = [7,1,4,3,8];
const max = arr.sort((a,b) => a-b)
.reduce((result,currentValue,index) => {
if(result < arr[index + 1] - currentValue) {
return arr[index + 1] - currentValue
}
return result
}, 0);
console.log(max);
类似,但使用 map
和 Math.max
let arr = [7,1,4,3,8];
const max2 = Math.max(...arr.sort((a,b) => a-b)
.map((v, i) => (++i < arr.length) ? Math.abs(v - arr[i]) : 0));
console.log(max2);
关于javascript - 什么是获得排序数组中连续元素之间最大差异的最佳解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58190748/