我试图在一个数字数组中找到第二大的数字,但最大的数字出现了两次,所以我不能直接从数组中删除它并选择新的最大数字。
array = [0, 3, 2, 5, 5]
(因此 3
是第二大值)
我有这段代码,我可以在其中显式返回 3,但它不适用于其他数组:
function getSecondLargest(nums) {
var sorted_array = nums.sort(function (a,b) {return a - b;});
var unique_sorted_array = sorted_array.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
return unique_sorted_array[unique_sorted_array.length - 2];
}
return unique_sorted_array[unique_sorted_array.length - 2];
如果我想让它更动态,有没有一种方法可以识别数组的最大值,然后将其与数组的每次迭代进行比较?
我当时想的是:
var greatestNum = sortedArray[-1]
while(greatestNum != i) do {
//check for the first number that doesn't equal greatestNum
}
如有任何帮助,我们将不胜感激。
最佳答案
您可以简单地创建一个 Set先比sort降序并取第一个索引元素
let array = [0, 3, 2, 5, 5]
let op = [...new Set(array)].sort((a,b) => b-a)[1]
console.log(op)
对于那些考虑效率的人。这是 IMO 的最佳方式
let array = [0, 3, 2, 5, 5]
let max = -Infinity
let secondMax = -Infinity
for(let i=0; i<array.length; i++){
if(array[i] > max){
secondMax = max
max = array[i]
}
}
console.log(secondMax)
关于javascript - 在具有最大整数重复项的数组中查找第二大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170380/