Thursday, January 19, 2012

How do you find if a Java array has duplicates?

How do you find if a Java array has duplicates?


Say you have a int[] hugeArray and want to find if it has huplicates in an efficient way, without iterating over the hugeArray twice – which is O(n²). You could use a HashSet, so the code will be like this (Java code snipet as image and as text, so you can copy):

[Java code snipet] Array has duplicates


/** © 2012 interviewqa4java.blogspot.com */
private static boolean hasDuplicates(int[] hugeArray) {
        Set<Integer> set = new HashSet<Integer>();
        for (int element : hugeArray) {
            if(set.contains(element)){
                return true;
            }
            set.add(element);
        }
        return false;
    }






No comments:

Post a Comment

Please, before starting to comment, evaluate if what you want to write is useful, respectful and positive. A kid may read this also.

Give a good example!