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?


------------

class Solution {
public:
    int singleNumber(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int ones = 0, twos = 0, not_three = 0;
        for (int i = 0; i < n; i++) {
            int x = A[i];
            twos |= ones & x;
            ones ^= x;
            not_three = ~(ones & twos);
            ones &= not_three;
            twos &= not_three;
        }
        
        return ones;
    }
};  


初始化 : ones包含只出现1次bit信息, twos包含所有出现两次的bit信息,not_three包含所有出现少于三次的bit信息

对数组中每个整数(x)进行以下操作:

1. twos |= ones & x      --  获得当前整数x与现有ones的交集,也就是出现两次的bit信息,把这些得到的出现两次的bit信息 或 到 twos上

2. ones ^= x,   分三种情况 : x出现1,2,3次, 除了出现两次外,ones将包含该数的bit信息

3. not_three = ~(ones & twos);  把当前非出现三次的bit信息赋值给 not_three

         4.  ones &= not_three;  从ones里边清除出现三次的bit信息
         5.  twos &= not_three;  从twos清除出现三次的bit信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值