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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值