1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| function fn(arr){ var res = undefined; var maxNums = [0, 0, 0]; var minNums = [0, 0]; var len = arr.length; var i, j, k;
for(i = 0; i < len; i++){ if(arr[i] < 0){ for(j = 0; j < 2; j++){ if(minNums[j] > arr[i]){ minNums.splice(j, 0, arr[i]); minNums.pop(); break; } } }else { for(k = 2; k >= 0; k--){ if(maxNums[k] < arr[i]){ maxNums.splice(k + 1, 0, arr[i]); maxNums.shift(); break; } } } }
if(maxNums[0] * maxNums[1] > minNums[0] * minNums[1]){ res = maxNums; }else { res = minNums.concat(maxNums[2]); } return res; }
console.log(fn([-1, -8, 3, 5, -7, 4, 9, 1, 2, 6, 8, 11, -4, -3])); console.log(fn([0, 0, 1, 0, 0, -2, -1]));
|