zoukankan      html  css  js  c++  java
  • 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.待续

  • 相关阅读:
    STM32-串口通信
    STM32-系统计时器(systick)
    字符串操作常用的函数
    基本MarkDown语法
    结构
    python入门
    贪心算法小结
    POJ1631_高深DP
    POJ3046ANT_COUNTING
    POJ1742coins
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4092404.html
Copyright © 2011-2022 走看看