- map
C++:
class Solution {
public:
int singleNumber(vector<int>& nums) {
std::map<int, int> map;
for ( int i = 0; i < nums.size(); ++i ) {
if ( map.find( nums[i] ) != map.end() ) {
map.erase( nums[i] );
} else {
map[nums[i]] = i;
}
}
for ( auto iterator : map ) {
return iterator.first;
}
return 0;
}
};
- 异或法
C++:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
for ( auto number : nums ) {
result ^= number;
}
return result;
}
};
网友评论