|
Second Highest Number in an Array
Find the second highest number in an integer array.
|
package com.bethecoder.tutorials.coding.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
/**
* Find second highest number in an integer array.
*/
public class SecondHighestNumberTest {
/**
* @param args
*/
public static void main(String[] args) {
Integer [] nums = { 1, 4, 6, 9, 9, 8, 8, 2, 2, 4};
System.out.println("Second highest number in " +
Arrays.toString(nums) + " : " + getSecondHighestNumber(nums));
nums = new Integer [] { 100000, 1001, 2222, 44444};
System.out.println("Second highest number in " +
Arrays.toString(nums) + " : " + getSecondHighestNumber(nums));
}
/**
* This method returns second highest number if available
* otherwise returns -1.
*
* @param nums
* @return
*/
private static int getSecondHighestNumber(Integer [] nums) {
if (nums == null || nums.length < 2) {
return -1;
}
List<Integer> uniqueNums = new ArrayList<Integer>(new HashSet<Integer>(Arrays.asList(nums)));
Collections.sort(uniqueNums);
return uniqueNums.get(uniqueNums.size() - 2); //get second element [0, 1, 2, .. n-2, n-1]
}
}
|
| |
It gives the following output,
Second highest number in [1, 4, 6, 9, 9, 8, 8, 2, 2, 4] : 8
Second highest number in [100000, 1001, 2222, 44444] : 44444
|
|