Given a non-empty 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?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
Solution :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <set> | |
class Solution | |
{ | |
public: | |
static int singleNumber( std::vector<int> nums ) | |
{ | |
unsigned int result = 0; | |
// Get all unique number and add them | |
std::set<int> mSet( nums.begin(), nums.end() ); | |
for( std::set<int>::iterator it = mSet.begin(); it != mSet.end(); it++ ) | |
{ | |
result += *it; | |
} | |
// we must have pairs , so double it | |
result = 2 * result; | |
// Reduce all the number to find what's left that must be the | |
// un-matched number | |
for( unsigned int i = 0; i < nums.size(); i++ ) | |
{ | |
result -= nums[i]; | |
} | |
return result; | |
} | |
}; | |
int main() | |
{ | |
std::vector<int> nums = { 4, 1, 2, 1, 2 }; | |
// should return 4 for this case | |
std::cout << Solution::singleNumber( nums ) << std::endl; | |
return 0; | |
} |