Leetcode题解14 136. 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?

很显然,这个解法不是最好的方式,留个坑,以后继续。

 public static int singleNumber(int[] nums) {
        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        int temp;
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.get(nums[i]) != null) {
                temp = hashMap.get(nums[i]);
                hashMap.put(nums[i], ++temp);
            } else {
                hashMap.put(nums[i], 1);
            }
        }
        Iterator it = hashMap.keySet().iterator();
        while (it.hasNext()) {
            int key = (int) it.next();
            for (int i = 0; i < hashMap.get(key); i++) {
                if (hashMap.get(key) == 1) {
                    return key;
                }
            }
        }
        return -1;
    }

你可能感兴趣的:(LeetCode)