136. Single Number 求數組中單一的數字

給定的整數的數組,除了其中一個元素出現一次,剩餘每個元素出現兩次。找出單獨出現的這個元素。

你應該有一個線性時間複雜度的算法。你能實現它,而無需使用額外的內存?

we use bitwise XOR to solve this problem :

first , we have to know the bitwise XOR in java

1、0 ^ N = N
2、N ^ N = 0
So..... if N is the single number

N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N

= (N1^N1) ^ (N2^N2) ^..............^ (Nx^Nx) ^ N

= 0 ^ 0 ^ ..........^ 0 ^ N

= N


public int singleNumber(int[] nums) {
    int ans =0;
    
    int len = nums.length;
    for(int i=0;i!=len;i++)
        ans ^= nums[i];
    
    return ans;
    
}

用異或的解法,牛逼


其他解法

public class Solution {
    public int singleNumber(int[] nums) {
        int count=1;
        int a=0;
        Map<Integer,Integer> map=new HashMap();
        for(int num:nums){
            if(!map.containsKey(num)) map.put(num,count);
            else map.put(num,count+1);
        }
        
        Set<Integer> ks = map.keySet();
        Iterator<Integer> it = ks.iterator();
        while (it.hasNext()) {
            Integer key = it.next();
            if(map.get(key)==1)    a=key;                       
        }
        return a;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章