LeetCode:136----只出现一次的数字

 第一次是使用HashMap解决的,但好像时间和空间都比较浪费。

class Solution {
        public int singleNumber(int[] nums) {
    	Map<Integer,Integer> map=new HashMap();
    	for(int n:nums) {
    		Integer val = map.get(n);
    		if(val==null) val=0;
    		map.put(n, val+1);
    	}
    	for(Map.Entry<Integer,Integer> entry:map.entrySet()) {
    		if(entry.getValue()==1) return entry.getKey();
    	}
    	return 0;
    }
}

后来看了题解才知道有更好的方法,即异或运算;原理如下:

  1. 交换律:a ^ b ^ c <=> a ^ c ^ b

  2. 任何数于0异或为任何数 0 ^ n => n

  3. 相同的数异或为0: n ^ n => 0

修改之后:

class Solution {
    public int singleNumber(int[] nums) {
    	int val=0;
    	for(int num:nums) {
    		val^=num;
    	}
    	return val;
    }
}
var code = "c999172f-1ca3-456e-8f83-c1ac4a22d302"
posted @ 2023-02-20 12:23  Godofball  阅读(32)  评论(0)    收藏  举报