首页 > 代码库 > Single Number

Single Number

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?

解决方案:

法1.用map记录每个数字出现的次数。map<int,int> m;若执行m[1],则m中有个键为1,值为0的键值对,后面是默认初始化为0。

所以这里的m[A[i]]=m[A[i]]+1;若A[i]第一次出现则它的值为0,然后加1,就为1啦。

class Solution {public:    int singleNumber(int A[], int n) {        map<int,int> m;        for(int i=0;i<n;++i)            m[A[i]]++;//m[A[i]]=m[A[i]]+1        map<int,int>::iterator it=m.begin();        for (it;it!=m.end();++it)        {            if((*it).second==1)                return (*it).first;        }    }};

法2.待续

 

Single Number