您的位置:首页 > 编程语言

LintCode【简单】82. 落单的数。代码及思路

2018-02-08 16:28 337 查看

题目要求:

给出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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: