我得到了一个问题:如何找到数组中最高的三个数字?
给定一个arrayOfInts,找到你可以从三个 整数获取highestProduct。
输入:var a = [1,7,9,2];预期输出:7 * 9 * 2 = 126
我们将如何解决这个问题?我写了代码但徒劳无功。
function highestProductIntegers(a){
var h1, h2,h3; //three highest number pointers.
a.forEach(function(val, index){
if(index=0){
h1 = val; //assign the first element to h1 (Highest 1)
}
h2 = val; //second to h2
if(val > h1){ //if second is greater than h1 make it h1 || h2 || h3
h3 = h2;
h2 = h1;
h1 = val;
}
else if(val<h1 && val > h2) //keep comparing for all elements.
h2 = val;
else if(val < h1 && val < h2)
h3 = val;
else if(val < h1 && val < h2 && val > h3)
h3=val;
});
return h1*h2*h3;
}
有没有更简单或有效的方法来解决这个问题?
排序然后乘以前3个数字。乘法的特性是这样的,你不需要比较产品。最大的数字是最大的产品。 – Forklift
这个问题比看起来更难:请注意,下面的答案都不适用于测试用例'[-50,-10,1,2,3]'。 –
@JeffBowman是的,我已经评论了有关事实的签名答案可能与您的意见有关。 – SaidbakR