A HashSet
is inherently unordered, so getting the N-th item from the set is meaningless. You have no idea what value you get. The algorithm is inherently arbitrary. Instead iterate the sorted array to get the N-th largest value, or use a TreeSet
which is not unordered.
Since you don't actually need the entire data in the sorted set you can remove items from the set as you go. Technically, since the set only ever has a maximum of 5 items if you do that each operation is O(1), making the whole algorithm O(n).
public int getNthLargestNum(int[] data, int n){
TreeSet<Integer> set = new TreeSet<Integer>();
foreach(int number : data)
{
set.add(number);
if(set.size() > 5)
set.pollFirst();
}
return set.first();
}