题目描述:
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
中文理解:给出一个数组里面,只有一个整数位单数次出现,其他均出现偶数次,找出该数。
解题思路:采用位运算,相同的数异或位运算结果为0,0与任何数异或位运算结果为这个数本身。
代码(java):
class Solution {
public int singleNumber(int[] nums) {
int res=nums[0];
for(int i=1;i<nums.length;i++){
res=res^nums[i];
}
return res;
}
}