Leetcode 136 : Single Number

问题描述:

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

思路:
用哈希表实现。把数值设为key,把出现的次数设为value。插入map前先检查,如果有这个元素,则替换原键值对的value为2;若没有这个元素,则插入该键值对且value为1.
难点在于搜索value=1的key。hashmap没有直接由value找key的操作,所以要扫描所有的key,如果这个key的value=1,则返回这个key。

代码如下:

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i =0; i<nums.length; i++){
            if (!map.containsKey(nums[i])){
                map.put(nums[i], 1);
            }
            else{
                map.replace(nums[i],2);
            }
        }
        for (Integer key : map.keySet()){
            if (map.get(key)==1){
                return key;
            }
        }
        return -1;
    }
}

时间复杂度: O(n)

巧妙方法:

class Solution {
  public int singleNumber(int[] nums) {
    int a = 0;
    for (int i : nums) {
      a ^= i;
    }
    return a;
  }
}

a xor b xor a = b
假如有5个元素{4,1,2,1,2}
4=1000
1=0001
2=0010

设a=0000
a xor 4 = 1000
1000 xor 1 = 1000 xor 0001 = 1001
1001 xor 2 = 1001 xor 0010 = 1011
1011 xor 1 = 1011 xor 0001 = 1010
1010 xor 2 = 1010 xor 0010 = 1000 = 4

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值