Problem: Single Number

Posted by Marcy on February 18, 2015

Question

Given an array of integers, every element appears twice except for one. Find that single one.

Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Solution 1

TODO

Code

class Solution {
    public int singleNumber(int[] nums) {
        Set<Integer> set = new HashSet();
        for(int i=0; i<nums.length; i++) {
            if(set.contains(nums[i])) {
                set.remove(nums[i]);
            }
            else {
                set.add(nums[i]);
            }
        }
        
        return set.iterator().next();
    }
}

Solution 2

TODO

Code

class Solution {
    public int singleNumber(int[] nums) {
        int xor = nums[0];
        for(int i=1; i<nums.length; i++) {
            xor = xor ^ nums[i];
        }
        
        return xor;
    }
}

Performance

TODO