1

Would this be the correct method to check whether an integer array contains duplicates? I wanted to pass in an int[] nums instead of Integer[], but couldn't get that to work.

public static boolean isUnique(Integer[] nums){
    return new HashSet<Integer>(Arrays.asList(nums)).size() == nums.length;
}
3
  • This gives you correct output right? So it is correct. Or you meant something else by saying - correct method? Commented Oct 25, 2013 at 15:14
  • @Rohit This does work - I'm wondering moreso if this is the best way. Commented Oct 25, 2013 at 15:16
  • here is a great answer to your question, showing several different methods and a benchmark. Commented Oct 25, 2013 at 15:16

2 Answers 2

4

You can do something like:

public static boolean isUnique(int[] nums){
    Set<Integer> set = new HashSet<>(nums.length);

    for (int a : nums) {
        if (!set.add(a))
            return false;
    }

    return true;
}

This is more of a short-circuit-esque approach than what you have, returning as soon as it encounters a duplicate. Not to mention it works with an int[] as you wanted. We are exploiting the fact that Set#add returns a boolean indicating whether the element being added is already present in the set.

Sign up to request clarification or add additional context in comments.

Comments

0

Whether Set or sorting is irrelevant here, and sorting is more optimal, less objects.

public static boolean isUnique(int[] nums) {
    if (nums.length <= 1) {
        return true;
    }
    int[] copy = Arrays.copyOf(nums);
    Arrays.sort(copy);

    int old = Integer.MAX_VALUE; // With at least 2 elems okay.
    for (int num : copy) {
        if (num == old) {
            return false;
        }
        old = num;
    }
    return true;
}

Addendum As commented slower, though saving memory.

3 Comments

"and sorting is more optimal, less objects.": Sorting is performed in O(n*log(n)), whereas adding stuff to a HashSet is performed in O(n). For large arrays, sorting is certainly worse...
@LukasEder: I thought creating n objects outweighted sorting ints. However testing revealed that from ca. 5000 upwards you are right (having much memory, 64 bit) - +1. With 10 000 sort was ca 5 times slower. P.S. remains in ms scope.
I doubt that the HashSet and its entries will escape eden space, so the GC can probably collect the whole HashSet shortly after leaving the method. The JVM has become pretty good at garbage collection... Note that the OP already has an Integer[] input array, not an int[] array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.