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];
Take two variables and initiliaze them with zero. Iterate through each element of the array and compare each number against these two number. If current number is greater than maxOne then maxOne = number and maxTwo = maxOne. Otherwise if it only greater than maxTwo then we only update maxTwo with current number.
Take input a stream of n integer elements, find the second largest element present. The given elements can contain duplicate elements as well. If only 0 or 1 element is given, the second largest should be INT_MIN ( - 2^31 ).
I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:
static int secondHighest(int... nums) { int high1 = Integer.MIN_VALUE; int high2 = Integer.MIN_VALUE; for (int num : nums) { if (num > high1) { high2 = high1; high1 = num; } else if (num > high2) { high2 = num; } } return high2; }
This is O(N)
in one pass. If you want to accept ties, then change to if (num >= high1)
, but as it is, it will return Integer.MIN_VALUE
if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE
if the array contains only the same number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With