Frage

I was implementing a code to return the nth Largest Number in an array, Following is the code I implemented;

public int getNthLargestNum(int [] givenArr, int n){

    int nTotal=0;
    int nNthNum = -1;

    // Remove Duplicates
    Set<Integer> o_hs = new TreeSet<Integer>();
    for(int insert=0; insert<givenArr.length; insert++)
    {o_hs.add(givenArr[insert]);}

    Iterator it  = o_hs.iterator();
    int count=0;

    while(it.hasNext()){
        if(count == n){

        // IF I MOVE THE LINE HERE
        // nNthNum = (Integer)it.next();

            break;
        }
        nNthNum = (Integer)it.next();
        count++; 
    }

return nNthNum;    
}

If I input the array givenArr[4,14,4,5,6,8,9] and n=2 the output is 5 for the above program but if I move the line nNthNum = (Integer)it.next(); inside the if loop it outputs 4.

So I was curious to know to iterate through the loop we should always implement it.next()?

War es hilfreich?

Lösung

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();
}

Andere Tipps

Yes, if you don't do it.next(), next element in collection will not be fetched.

it.hasNext() call will not advance pointer to next element in collection.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top