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;
}
};
- int singleNumber(int A[], int n)
- {
- int one = 0, two = 0; //每一位出现一次或者三次的其中一种在one中,每一位出现两次和三次的,都在two中。three中保存位出现三次的。
- for (int i = 0; i < n; i++)
- {
- two |= A[i] & one; //&代表one中是否出现过某一位。
- one ^= A[i]; //^代表当切仅当第奇次出现。 |= 是保存位。
- int three = one & two; //因为出现了两次的位,one就一定不会出现(异或掉了),所以只有出现三次的位才会在three中出现。
- one &= ~three; //消除位出现三次的。
- two &= ~three;
- }
- return one;
- }