Given a non-empty array of integers, every element appears twice except forone. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement itwithoutusing extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
解答
/**
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
*/publicclassSingleNumber {publicstaticintsingleNumber(int[] nums) {
/**方法一:最直观的想法,把数组中的所有数遍历一遍,从第一个开始,看有几个相同。
* 这样写复杂度为o(n^2)复杂度太高。 有兴趣的小伙伴可以自己动手写一遍
*//**
* 方法二借助hashmap遍历一边数组,记录数组中出现的次数,最后取出value为一的key
* 这里也省了,小伙伴自己动手写一遍
*//**
* 这里主要讲解方法三:使用异或运算符
* 举个例子:如果 a^b^a = b
* a^b^a^b^c = c
* 1^1^2=2
* 这样一来就很简单了
*/int p=nums[0];
for (int i=1;i<nums.length;i++){
p^=nums[i];
}
return p;
}
publicstaticvoidmain(String[] args) {
int [] nums={5,6,6,3,8,3,8,5,7};
System.out.println(singleNumber(nums));
}
}