136. Single Number - Easy

Given a non-empty 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?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

 

M1: bit maipulation

xor ^
Concept
If we take XOR of zero and some bit, it will return that bit ==> a xor 0 = a
If we take XOR of two same bits, it will return 0 ==> a xor a = 0
a xor b xor a = (a xor a) xor b = 0 xor b = b
So we can XOR all bits together to find the unique number.

public class Solution {
    /**
     * @param A: An integer array
     * @return: An integer
     */
    public int singleNumber(int[] A) {
        // write your code here
        int res = 0;
        for(int a : A) {
            res ^= a;
        }
        return res;
    }
}



M2: hashmap

时间复杂度O(n),空间复杂度O(n)

public class Solution {
    /**
     * @param A: An integer array
     * @return: An integer
     */
    public int singleNumber(int[] A) {
        // write your code here
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int a : A) {
            map.put(a, map.getOrDefault(a, 0) + 1);
        }
        int res = 0;
        for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if(entry.getValue() == 1)
                res = entry.getKey();
        }
        return res;
    }
}

 

M3: hashset

遍历数组,如果不能往set里添加元素,说明重复,将该元素移除。最后set里剩下的就是唯一一个只出现一次的元素

public class Solution {
    /**
     * @param A: An integer array
     * @return: An integer
     */
    public int singleNumber(int[] A) {
        // write your code here
        Set<Integer> set = new HashSet<>();
        for(int a : A) {
            if(!set.add(a))
                set.remove(a);
        }
        return set.iterator().next();
    }
}

 

posted @ 2018-11-20 13:01  fatttcat  阅读(113)  评论(0编辑  收藏  举报