zoukankan      html  css  js  c++  java
  • LeetCode-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?

    class Solution {
    public:
        void  toTribit(vector<int>& bits,int val){
            
            if(val<0){
                bits[31]=1;
                val=-val;
            }
            else bits[31]=0;
            int ind=0;
            while(val>0){
                bits[ind]=val%3;
                val/=3;
                ind++;
            }
            for(int i=ind;i<bits.size()-1;i++)bits[i]=0;
        }
        void Xor(vector<int>& bits1,vector<int>& bits2){
            for(int i=0;i<bits1.size();i++){
                bits1[i]=(bits1[i]+bits2[i])%3;
            }
        }
        int tribitToInt(vector<int>& bits){
            int ret=0;
            if(bits[31]==1){
                for(int i=bits.size()-2;i>=0;i--){
                    ret*=3;
                    ret-=bits[i];
                }
                if(ret==0)return 0x80000000;
            }
            else{
                for(int i=bits.size()-2;i>=0;i--){
                    ret*=3;
                    ret+=bits[i];
                }
            }
            return ret;
        }
        int singleNumber(int A[], int n) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            vector<int> bits1,bits2;
            if(n<1)return 0;
            bits1.resize(32,0);
            bits2.resize(32,0);
            toTribit(bits1,A[0]);
        //    cout<<tribitToInt(bits1)<<endl;
            for(int i=1;i<n;i++){
                toTribit(bits2,A[i]);
                Xor(bits1,bits2);
            //    cout<<tribitToInt(bits2)<<endl;
            }
            if(n%3==2){
                for(int i=0;i<32;i++){
                    switch(bits1[i]){
                    case 0: bits1[i]=0;break;
                    case 1:bits1[i]=2;break;
                    case 2:bits1[i]=1;break;
                    default:break;
                    }
                }
            }
            return tribitToInt(bits1);
        }
    };
    View Code
  • 相关阅读:
    hbase shell-namespace(命名空间指令)
    hbase shell-general(常规指令)
    hbase shell概述
    Codeforces Round #412 div2 ABCD
    Educational Codeforces Round 19
    CSU 1786 莫队+KDTree
    cdq分治入门and持续学习orz
    VK Cup 2017
    HRBUST 2072 树上求最大异或路径值
    UvaLive 5811 概率DP
  • 原文地址:https://www.cnblogs.com/superzrx/p/3350629.html
Copyright © 2011-2022 走看看