Level:
Easy
题目描述:
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,那么我们可以将整个数组中的元素进行异或最后的结果肯定就是只出现一次的数。
代码:
class Solution {
public int singleNumber(int[] nums) {
int xor=0;
for(int i=0;i<nums.length;i++){
xor=xor^nums[i];
}
return xor;
}
}