LeetCode

Single Number

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?

Java

public class Solution {
    public int singleNumber(int[] nums) {
        if(nums.length < 1) {
            return 0;
        }

        int len = nums.length;
        Map<Integer, Integer> count = new HashMap<Integer, Integer>();

        for(int i = 0; i < len; i++) {
            if(count.containsKey(nums[i])) {
                count.put(nums[i], count.get(nums[i]) + 1);
            } else {
                count.put(nums[i], 1);
            }
        }

        for(int i : count.keySet()) {
            if(count.get(i) != 2) {
                return i;
            } 
        }
        return 0;
    }
}