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

    137. Single Number II

     
     
    Total Accepted: 80477 Total Submissions: 214984 Difficulty: Medium

    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?

    Subscribe to see which companies asked this question

    Code:

    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int ret = 0;
            int mask = 1;
            while(mask)
            {
                int countOne = 0;   //number of digit 1
                for(int i = 0; i < nums.size(); i ++)
                {
                    if(nums[i] & mask)
                        countOne ++;
                }
                if(countOne % 3 == 1)
                    ret |= mask;
                mask <<= 1;
            }
            return ret;
        }
    };

    1. int singleNumber(int A[], int n)  
    2. {  
    3.     int one = 0, two = 0;   //每一位出现一次或者三次的其中一种在one中,每一位出现两次和三次的,都在two中。three中保存位出现三次的。
    4.     for (int i = 0; i < n; i++)  
    5.     {  
    6.         two |= A[i] & one;  //&代表one中是否出现过某一位。
    7.         one ^= A[i];  //^代表当切仅当第奇次出现。 |=  是保存位。
    8.         int three = one & two;  //因为出现了两次的位,one就一定不会出现(异或掉了),所以只有出现三次的位才会在three中出现。
    9.         one &= ~three;  //消除位出现三次的。
    10.         two &= ~three;  
    11.     }  
    12.     return one;  
  • 相关阅读:
    HDU 2121 Ice_cream’s world II 不定根最小树形图
    POJ 3164 Command Network 最小树形图
    POJ 3723 Conscription 最小生成树
    UVA 1175 Ladies' Choice 稳定婚姻问题
    BZOJ 2753 [SCOI2012] 滑雪和时间胶囊 最小生成树
    BZOJ 1854: [Scoi2010]游戏 无向图判环
    HDU 3974 Assign the task 暴力/线段树
    Codeforces Round #302 (Div. 2) D. Destroying Roads 最短路
    uoj 67 新年的毒瘤 割点
    蓝桥
  • 原文地址:https://www.cnblogs.com/Alex0111/p/5373811.html
Copyright © 2011-2022 走看看