描述
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?
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
例子
思路
- 异或
两个相同的数异或操作【不进位的二进制加法操作】后结果为0,且异或操作满足结合律和交换律,把所有的数异或起来,得到的数就是只出现一次的数
答案
- python
def singleNumber(self, nums: List[int]) -> int:
a=0
for n in nums:
a ^= n
return a
- c++
int singleNumber(vector<int>& nums) {
int a = 0;
for (int n : nums)
a ^= n;
return a;
}
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for(int n:nums)
res = res^n;
return res;
}
}