05 August 2008
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:
1
2
Input: [2,2,1]
Output: 1
Example 2:
1
2
Input: [4,1,2,1,2]
Output: 4
给一个数组,每个数字出现两次,找出只出现过一次的数字。中规中矩用HashMap来统计次数自然是没什么难度,这里用位操作中XOR,当两个数相同的时候为0,位数相互进行XOR后,最后的结果一定会是只出现一次的元素。
1
2
3
4
5
6
7
8
9
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
}