为了提高我的一般解决问题的能力,我最近订阅了Daily Coding Problem。提出的挑战之一有以下描述:
优步要求这个问题。
给定一个整数数组,返回一个新数组,使得新数组的索引i处的每个元素都是原始数组中除i处的数字之外的所有数字的乘积。
例如,如果我们的输入是[1,2,3,4,5],则预期输出将是[120,60,40,30,24]。如果我们的输入为[3,2,1],则预期输出为[2,3,6]。
后续行动:如果你不能使用师?
我使用以下函数在几分钟内解决了这个特殊挑战:
function solution(_input) {
return _input.map((_number, _index, _list) => {
return _list.reduce((_accumulator, _currentValue, _currentIndex) => {
return _accumulator * ((_index !== _currentIndex) ? _currentValue : 1);
}, 1);
});
}
我的功能很有效,完美匹配每个预期的输出...但这让我对挑战的最后一行感到好奇。
如何使用除法来解决这个问题?
作为@Steve alluded in the comments,你会:
const product = input.reduce((accumulator, value) => accumulator * value, 1);
return input.map(value => product / value);
这降低了操作复杂度从O(N2)到O(N)(如果我没有记错的话),因为我们正在删除嵌套循环。
const func = input => {
const product = input.reduce((accumulator, value) => accumulator * value, 1);
return input.map(value => product / value);
}
console.log(func([1, 2, 3, 4, 5]));