题目要求:
给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。
样例
给出 [1,2,2,1,3,4,3],返回 4
挑战
一次遍历,常数级的额外空间复杂度
思路:
一次遍历,但是额外的空间复杂度是O(n)。
申请动态容器vector ,遍历一次A,如果A[i]和recult里有一样的,就把recult里的删掉,如果没有删掉,就加进去。最后只剩一个,return 就行了。
class Solution {
public:
/*
* @param A: An integer array
* @return: An integer
*/
int singleNumber(vector<int> &A) {
// write your code here
int i, j;
bool iserase;
vector<int> result;
for(i = 0; i < A.size(); i++){
iserase = false;
for(j = 0; j < result.size(); j++){
if(result[j] == A[i]){
cout<<result[j]<<" * ";
result.erase(result.begin()+j);
iserase = true;
break;
}
}
if(!iserase) result.push_back(A[i]);
}
cout<<result.size();
return result[0];
}
};