猿问

查找数组中第二高的数字

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


int second highest = score[0];  

if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest)   

    second_highest = score[i];


婷婷同学_
浏览 399回答 3
3回答

有只小跳蛙

我不相信做您所做的事情可以解决问题。我认为这掩盖了您逻辑中的另一个问题。找到第二高实际上很简单:&nbsp;static int secondHighest(int... nums) {&nbsp; &nbsp; int high1 = Integer.MIN_VALUE;&nbsp; &nbsp; int high2 = Integer.MIN_VALUE;&nbsp; &nbsp; for (int num : nums) {&nbsp; &nbsp; &nbsp; if (num > high1) {&nbsp; &nbsp; &nbsp; &nbsp; high2 = high1;&nbsp; &nbsp; &nbsp; &nbsp; high1 = num;&nbsp; &nbsp; &nbsp; } else if (num > high2) {&nbsp; &nbsp; &nbsp; &nbsp; high2 = num;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return high2;&nbsp;}这是O(N)一口气。如果您想接受联系,则更改为if (num >= high1),但按原样,Integer.MIN_VALUE如果数组中至少有2个元素,它将返回。Integer.MIN_VALUE如果数组仅包含相同的数字,它也将返回。

呼啦一阵风

// Initialize these to the smallest value possibleint highest = Integer.MIN_VALUE;int secondHighest = Integer.MIN_VALUE;// Loop over the arrayfor (int i = 0; i < array.Length; i++) {&nbsp; &nbsp; // If we've found a new highest number...&nbsp; &nbsp; if (array[i] > highest) {&nbsp; &nbsp; &nbsp; &nbsp; // ...shift the current highest number to second highest&nbsp; &nbsp; &nbsp; &nbsp; secondHighest = highest;&nbsp; &nbsp; &nbsp; &nbsp; // ...and set the new highest.&nbsp; &nbsp; &nbsp; &nbsp; highest = array[i];&nbsp; &nbsp; } else if (array[i] > secondHighest)&nbsp; &nbsp; &nbsp; &nbsp; // Just replace the second highest&nbsp; &nbsp; &nbsp; &nbsp; secondHighest = array[i];&nbsp; &nbsp; }}// After exiting the loop, secondHighest now represents the second// largest value in the array编辑:哎呀 谢谢你们指出我的错误。立即修复。

达令说

如果将first_highest最初设置为的第一个元素已经是最高元素,则在找到下一个元素时应将其重新分配给新元素。就是说,它被初始化为98,应该被设置为56。但是,56并不高于98,因此除非您进行检查,否则它不会被设置。如果最高编号出现两次,则将导致第二个最高值,而不是对数组进行排序时会找到的第二个元素。
随时随地看视频慕课网APP

相关分类

Java
我要回答