gpt4 book ai didi

javascript - 优化 javascript 代码以在数组中找到 3 个最大的元素及其索引?

转载 作者:数据小太阳 更新时间:2023-10-29 03:58:49 26 4
gpt4 key购买 nike

我需要此 javascript 代码的更优化版本来查找数组中的 3 个最大值。我需要获得最大数字的索引。有没有其他更简单的方法来解决这个问题?

var maxIndex = new Array();
var maxPoints = new Array();
var scoreByPattern = new Array(93, 17, 56, 91, 98, 33, 9, 38, 55, 78, 29, 81, 60);

function findLargest3() {
maxPoints[0] = 0;
maxPoints[1] = 0;
maxPoints[2] = 0;

for (i = 0; i < scoreByPattern.length; i++) {
if (scoreByPattern[i] > maxPoints[0]) {
maxPoints[0] = scoreByPattern[i];
maxIndex[0] = i;
}
}

for (i = 0; i < scoreByPattern.length; i++) {
if (scoreByPattern[i] > maxPoints[1] && scoreByPattern[i] < maxPoints[0]) {
maxPoints[1] = scoreByPattern[i];
maxIndex[1] = i;
}
}

for (i = 0; i < scoreByPattern.length; i++) {
if (scoreByPattern[i] > maxPoints[2] && scoreByPattern[i] < maxPoints[1]) {
maxPoints[2] = scoreByPattern[i];
maxIndex[2] = i;
}
}

console.log(scoreByPattern + "/******/" + maxPoints[0] + "/" + maxPoints[1] + "/" + maxPoints[2]);
//alert(maxIndex);
}

findLargest3();

最佳答案

修改版

我修改了我的答案以使其更通用。它搜索数组中 n 个最大元素的索引:

var scoreByPattern = [93,255,17,56,91,98,33,9,38,55,78,29,81,60];

function findIndicesOfMax(inp, count) {
var outp = [];
for (var i = 0; i < inp.length; i++) {
outp.push(i); // add index to output array
if (outp.length > count) {
outp.sort(function(a, b) { return inp[b] - inp[a]; }); // descending sort the output array
outp.pop(); // remove the last index (index of smallest element in output array)
}
}
return outp;
}

// show original array
console.log(scoreByPattern);

// get indices of 3 greatest elements
var indices = findIndicesOfMax(scoreByPattern, 3);
console.log(indices);

// show 3 greatest scores
for (var i = 0; i < indices.length; i++)
console.log(scoreByPattern[indices[i]]);

这是一个jsFiddle

关于javascript - 优化 javascript 代码以在数组中找到 3 个最大的元素及其索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11792158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com