LeetCode 137 Single Number II 解题报告

Single Number II
Total Accepted: 44725 Total Submissions: 128964

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?

这个题目是,给定一个序列,所有的数字都出现三次,只有一个出现一次,找出这个数字。 如果是出现两次的话,我们可以使用异或,异或两次就是0了,然后剩余的就是那个单独的数字。
如果是出现三次的话,我们可以这样实现:我们用一个32容量的数组储存当前位置,bit1出现的次数。最后的时候我们把每个次数模3,这样出现3次的就被模为0了。
例如:
3组数字
1 0 0
0 1 0
1 0 0
1 0 0
把所有1加起来,运算的结果是
3 1 0
我们把各位模3结果就是0 1 0即是,单独的数字。
最后把这个数字转换成数字即可,但是需要注意,如果最高位是1的话,也就是负数,需要取反再加一。

class Solution {
public:
    int singleNumber(int A[], int n) {
        vector<int> bitMod3(32, 0);
        int result = 0;
        for(int i = 0; i < n; ++i)
        {
            for(int j = 0; j < 32; ++j)
            {
                if(A[i] >> j & 1 == 1)
                    bitMod3[j]++;
            }
        }
        for_each(bitMod3.begin(), bitMod3.end(), [](int &x)
        {
            x %= 3;
        });
         for(int i = 0; i < 32; ++i)
        {
            if(bitMod3[i] ^ bitMod3[31]) //如果是负数各位取反
                result += pow(2, i);
        }
        if(bitMod3[31])
        {
            ++result;
            result = -result;
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值