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;
}
Keith
  • 95
  • 1
  • 2
  • 10
  • This gives you correct output right? So it is correct. Or you meant something else by saying - *correct method*? – Rohit Jain Oct 25 '13 at 15:14
  • @Rohit This does work - I'm wondering moreso if this is the best way. – Keith Oct 25 '13 at 15:16
  • [here](http://stackoverflow.com/a/3951563/1829930) is a great answer to your question, showing several different methods and a benchmark. – Robin Krahl Oct 25 '13 at 15:16

2 Answers2

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 3
    *"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... – Lukas Eder Oct 25 '13 at 15:25
  • @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. – Joop Eggen Oct 25 '13 at 15:50
  • 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 – Lukas Eder Oct 25 '13 at 17:18