1 题目描述
现在有一个整数类型的数组,数组中素只有一个元素只出现一次,其余的元素都出现两次。
注意:
你需要给出一个线性时间复杂度的算法,你能在不使用额外内存空间的情况下解决这个问题么?
Given an 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?
示例1
输入
[1,0,1]
输出
0
运行时间:3ms
2 解题思路
异或 使用异或操作后,两个相同的数字异或为0。所以数组中的所有数字异或后为所求数字。
3 代码实现
class Solution {
public:
/**
*
* @param A int整型一维数组
* @param n int A数组长度
* @return int整型
*/
int singleNumber(int* A, int n) {
// write code here
int singleNum = 0;
for(int i = 0; i < n; i++)
singleNum ^= A[i];
return singleNum;
}
};
4 运行结果
运行时间: 3ms
占用内存:504k