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

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

问题描述

我很难理解该方法背后的逻辑,以找到数组中第二高的数字。使用的方法是找到数组中的最高值但小于先前的最高值(已经找到)。我仍然无法弄清楚的是为什么 || high_score == second_highest 是必要的。例如,我输入了三个数字:98,56,3。没有它,最高和第二高都是98.请解释。

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];


推荐答案

我看到的答案如果有两个相同的话就不会工作如下例所示的最大数字。

The answers I saw wont work if there are two same largest numbers like the below example.

        int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 8, 9,9 };
        SortedSet<Integer> set = new TreeSet<Integer>();
        for (int i: randomIntegers) {
            set.add(i);
        }
        // Remove the maximum value; print the largest remaining item
        set.remove(set.last());
        System.out.println(set.last());

我已从Set中删除它而不是从数组

I have removed it from the Set not from the Array

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

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