首页 > 其他 > 详细

Single Number

时间:2014-11-12 16:13:15      阅读:272      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/fightformylife/p/4092404.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!