查找数组中第二大的数字 [英] Finding the second highest number in array

查看:24
本文介绍了查找数组中第二大的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解在数组中找到第二大数字的方法背后的逻辑.使用的方法是在数组中找到最高但小于前一个最高(已经找到)的方法.我仍然想不通的是为什么 ||highest_score == second_highest 是必要的.比如我输入三个数字:98、56、3.没有它,最高和次高都是98.请解释.

int 第二高 = score[0];if (score[i] > second_highest && score[i] <highest_score ||highest_score == second_highest)second_highest = score[i];

解决方案

let array = [0,12,74,26,82,176,189,8,55,3,189];让最高=0;让 secondHighest = 0;for (let i = 0; i 

I'm having difficulty to understand the logic behind the method to find the second highest number in array. The method used is to find the highest in the array but less than the previous highest (which has already been found). The thing that I still can't figure it out is why || highest_score == second_highest is necessary. For example I input three numbers: 98, 56, 3. Without it, both highest and second highest would be 98. Please explain.

int second highest = score[0];  
if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest)   
    second_highest = score[i];

解决方案

let array = [0,12,74,26,82,176,189,8,55,3,189]; 
let highest=0 ;
let secondHighest = 0;
for (let i = 0; i < array.length; i++) { 
if (array[i] > highest) { 
    // ...shift the current highest number to second highest
    secondHighest = highest; 
    // ...and set the new highest.
    highest = array[i]; 
} else if (highest > array[i] > secondHighest) { 
   // Just replace the second highest
   secondHighest = array[i]; 
  }
}
console.log(secondHighest);

这篇关于查找数组中第二大的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆