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;  
原文地址:https://www.cnblogs.com/Alex0111/p/5373811.html