zoukankan      html  css  js  c++  java
  • Single Number II

    Given an array of integers, every element appears three times except for one. Find that single one.

    Note:
    Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

    题目思路一:这道题要求时间复杂度是O(n),而且要求你不借用空间来实现。但是这道题我能想到的就是兼用map来实现。遍历数组,找出那个只出现一次的元素。

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

    题目思路二:这道题如果不借用空间来实现,可以使用位运算,但是这要求你位运算能力很强,然而我不会运用。网上说是,对于除出现一次之外的所有整数,其二进制表示中每一位1出现的次数是3的整数倍,将所有这些1清零(mod 3),剩下的就是最终的数,这种思路主要是用二进制模拟三进制。声明定义三个变量,分别标记出现一次,二次,三次的,每处理一个数的时候分别计算异或、与、非(出现三次时前两个变量都是1,取反后利用第三个变量清楚改数),然后第一个变量剩下的就是只出现一次的数。

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int one=0;
            int two=0;
            int three=0;
            for(int i=0;i<n;i++)
            {
                two|=(A[i]&one);
                one^=A[i];
                three=~(one&two);
                one&=three;
                two&=three;
            }
            return one;
        }
    };
  • 相关阅读:
    ceph简易安装
    ceph安装
    nova计算节点部署
    onva控制节点部署
    nova介绍
    image部署
    glance镜像介绍
    keystone部署
    keystone介绍
    rabbimtq消息队列部署
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3595568.html
Copyright © 2011-2022 走看看