136. Single Number

问题描述:一个数组中只有个一个数字出现了一次,其他的数字都出现两次,找出那个出现一次的。
提示:你的算法应在线性时间内完成,且不使用额外的存储空间。
思路:使用map可以在线性时间内完成,但是不使用额外的存储空间却无法做到。
原代码

    public int singleNumber(int[] nums) {
        int length=nums.length;
        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int i=0;i<length;i++){
            if(map.containsKey(nums[i]))
                map.put(nums[i],map.get(nums[i])+1);
            else
                map.put(nums[i],1);
        }
        for(int j=0;j<length;j++){
            if(map.get(nums[j])==1)
                return nums[j];
        }
        return 0;
    }

最佳答案:

    public int singleNumber(int[] nums) {
        if (nums == null || nums.length == 0) {
            return Integer.MIN_VALUE;
        }
        int res = nums[0];
        for (int i = 1; i < nums.length; i++) {
            res ^= nums[i];
        }
        return res;
    }

不得不说最佳答案很好的利用了题设。其它数字都出现两次保证异或操作后将全是0。而0异或只出现一次的数字将为原数字。真是个精妙的答案。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值