【问题标题】:Find 2nd largest value in an array that has duplicates of the largest integer在具有最大整数重复项的数组中查找第二大值
【发布时间】:2019-08-05 19:29:06
【问题描述】:

我试图在一个数字数组中找到第二大的数字,但最大的数字出现了两次,所以我不能只是从数组中删除它并选择新的最大数字。

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
}

任何帮助将不胜感激。

【问题讨论】:

  • 数组所有元素都相等的情况需要处理吗?或者当数组长度小于 2 时?
  • 这不是必需的,但这可能对将来查找此内容的任何人都有好处。

标签: javascript arrays while-loop


【解决方案1】:

您可以简单地先创建一个Set,然后以降序创建sort,然后获取第一个索引元素

let array = [0, 3, 2, 5, 5]

let op = [...new Set(array)].sort((a,b) => b-a)[1]

console.log(op)

对于那些从效率角度思考的人。这是国际海事组织的最佳方式

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)

【讨论】:

  • 如果你懒也可以.sort().reverse()
  • @GetOffMyLawn 是的,但是当你可以一次性完成时,这就是两次做同样的事情
  • @Code Maniac +1 第二个。这对我来说是新的
  • 感谢@CodeManiac - 非常简洁的答案,我很感激您在“运行代码 sn-p”中添加了您的解决方案
【解决方案2】:

我建议做更多类似的事情

const nums = [0, 3, 2, 5, 5];
nums.sort(function (a,b) {return b - a;})

for (let i = 1; i < nums.length; i++) {
  if (nums[0] !== nums[i]) {
    return nums[i];
  }
}

这应该比转换为集合并返回要高效得多(尤其是在内存方面)...

【讨论】:

  • 附注:当您谈论速度和性能时,即使没有排序也应该这样做。在这种情况下,可以只使用两个变量和简单的 for 循环
【解决方案3】:

试试这个:

var intArray = stringArray.map(nums); // now let's sort and  take the second element :

var second = intArray.sort(function(a,b){return b-a})[1];

};

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多