Java - Using Set API - Simple And Probably Practical


  • -2
    J

    Here is my accepted code for Java using two sets. Of course it uses extra memory but much simple to follow.

    Java Set interface has a add method, that returns false if object is already present. So I am using it to popular seen twice or more set. This can be done in one pass and than removeAll call will clear all duplicates from first set. So only non duplicate will be left. This will work for any number of duplicates.

    Let me know if we can improve this.

    public int singleNumber(int[] nums) {
        Set<Integer> intSet = new HashSet<>(nums.length);
        Set<Integer> seenTwice = new HashSet<>(nums.length);
        for(int n : nums) {
            if(!intSet.add(n)) {
                seenTwice.add(n);
            }
        }
        intSet.removeAll(seenTwice);
        return intSet.iterator().next();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.