我正在试图弄清楚如何找到三个最小的数字。我先得到2,但我不确定如何找到第三个。我不能使用任何改变原始数组的方法。谢谢。
let max_1 = 0;
let max_2 = 0;
let max_3 = 0;
for(let i=0; i<compare.length; i++){
let nr = +compare[i];
if(nr > max_1){
max_2 = max_1;
max_1 = nr;
}else if(nr < max_1 && nr > max_2){
?
}
}
答案 0 :(得分:1)
尝试以下方法:
var arr1 = [1,2,4,5,3,3,2];
let arr = [...new Set(arr1)];
var i, first, second, third;
third = first = second = 2147483647;
for (i = 0; i < arr.length ; i ++)
{
if (arr[i] < first)
{
third = second;
second = first;
first = arr[i];
}
else if (arr[i] < second)
{
third = second;
second = arr[i];
}
else if (arr[i] < third)
third = arr[i];
}
console.log(first+ " "+ second+" "+ third);
&#13;
答案 1 :(得分:0)
你可以使用如下的reduce - 它将返回一个包含3个最小数字的数组。
const array = [1,2,3,4,5,6,7,-1,-2, -2];
const threeSmallest = [...new Set(array)].reduce((a, b) => {
if (a.length < 3) return a.concat(b);
a.sort((x,y) => y - x);
let index = a.findIndex(e => e > b);
if (index > -1) {
a.splice(index, 1);
return a.concat(b);
}
return a;
},[]);
console.log(threeSmallest);
&#13;