[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?

题意:给定数组,除一个数仅出现一次外,其余都出现三次,找到仅出现一次的数字。

思路:这题不能延续single number的解法,但是思路可以向逻辑运算符那边靠。这题我开始没有想出来,这个逻辑运算对我而言是一个大坑。看了Grandyang的博客才明白。这里给出原博客中的解释:用3个整数来表示INT的各位的出现次数情况,one表示出现了1次,two表示出现了2次。当出现3次的时候该位清零。最后答案就是one的值,

ones 代表第ith 位只出现一次的掩码变量;twos 代表第ith 位只出现两次的掩码变量;threes 代表第ith 位只出现三次的掩码变量。

博主的个人理解经验是:写出一个例子,按照程序走一遍。

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) 
 4     {
 5         int one=0,two=0,three=0;
 6         for(int i=0;i<n;++i)
 7         {
 8             two |=one&A[i];
 9             one ^=A[i];
10             three=one&two;
11             one &=~three;
12             two &=~three;
13         }    
14         return one;
15     }
16 };

原博客中还给出了Single Number III

原文地址:https://www.cnblogs.com/love-yh/p/7198983.html