题意:有一个整型数组,其中只有一个数是只出现一次,其余均出现两次,请找出只出现一次的那个数并输出
public class Solution {
public int singleNumber(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int temp = nums[0];
for(int i = 1; i < nums.length; i++) {
temp ^= nums[i];
}
return temp;
}
}
解题思路:
一般思路,可能会用Map做缓存再遍历寻找;但如果不额外开辟空间怎么做?
由于是整型数,我们可以考虑用位运算:
关键点:a^b=b^a,0^c=c
举个栗子:int[] nums = {a, a, b, c, c, d, b};
则a^a^b^c^c^d^b=a^a^b^b^c^c^d=……=0^d=d