码迷,mamicode.com
首页 > 其他好文 > 详细

Single Number

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

标签:style   blog   io   color   ar   sp   for   div   on   

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

标签:style   blog   io   color   ar   sp   for   div   on   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!