描述: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?
题目要求O(n)时间复杂度,O(1)空间复杂度。
思路1:初步使用暴力搜索,遍历数组,发现两个元素相等,则将这两个元素的标志位置为1,最后返回标志位为0的元素即可。时间复杂度O(n^2)没有AC,Status:Time Limit Exceed
class Solution {
public:
int singleNumber(int A[], int n) { vector <int> flag(n,); for(int i = ; i < n; i++) {
if(flag[i] == )
continue;
else {
for(int j = i + ; j < n; j++) {
if(A[i] == A[j]) {
flag[i] = ;
flag[j] = ;
}
}
}
} for(int i = ; i < n; i++) {
if(flag[i] == )
return A[i];
}
}
};
思路2:利用异或操作。异或的性质1:交换律a ^ b = b ^ a,性质2:0 ^ a = a。于是利用交换律可以将数组假想成相同元素全部相邻,于是将所有元素依次做异或操作,相同元素异或为0,最终剩下的元素就为Single Number。时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int singleNumber(int A[], int n) { //异或
int elem = ;
for(int i = ; i < n ; i++) {
elem = elem ^ A[i];
} return elem;
}
};