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?

方法一: COPY FROM:http://blog.youkuaiyun.com/lanxu_yy/article/details/17437891

思路:

一个比较好的方法是从位运算来考虑。每一位是0或1,由于除了一个数其他数都出现三次,我们可以检测出每一位出现三次的位运算结果再加上最后一位即可。

代码:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class Solution {  
  2. public:  
  3.     int singleNumber(int A[], int n) {  
  4.         int ones = 0, twos = 0, threes = 0;  
  5.         for(int i = 0; i < n; i++)  
  6.         {  
  7.             threes = twos & A[i]; //已经出现两次并且再次出现  
  8.             twos = twos | ones & A[i]; //曾经出现两次的或者曾经出现一次但是再次出现的  
  9.             ones = ones | A[i]; //出现一次的  
  10.               
  11.             twos = twos & ~threes; //当某一位出现三次后,我们就从出现两次中消除该位  
  12.             ones = ones & ~threes; //当某一位出现三次后,我们就从出现一次中消除该位  
  13.         }  
  14.         return ones; //twos, threes最终都为0.ones是只出现一次的数  
  15.     }  
  16. };  

方法二: COPY FROM:http://www.tuicool.com/articles/UjQV7n

题目分析: 对于除出现一次之外的所有的整数,其二进制表示中每一位1出现的次数是3的整数倍,将所有这些1清零,剩下的就是最终的数。 用ones记录到当前计算的变量为止,二进制1出现“1次”(mod 3 之后的 1)的数位。用twos记录到当前计算的变量为止,二进制1出现“2次”(mod 3 之后的 2)的数位。当ones和twos中的某一位同时为1时表示二进制1出现3次,此时需要清零。即  用二进制模拟三进制计算 。最终ones记录的是最终结果。 时间复杂度: O(n) 示例代码:
int singleNumber(int A[], int n) {
    int ones = 0, twos = 0, xthrees = 0;
    for(int i = 0; i < n; ++i) {
        twos |= (ones & A[i]);
        ones ^= A[i];
        xthrees = ~(ones & twos);
        ones &= xthrees;
        twos &= xthrees;
    }

    return ones;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值