[LeetCode]*137.Single Number II

160 篇文章 28 订阅
【题目】

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?

【题意】

给定一个整数数组,每个元素出现了三次,除了一个。找出那个出现一次的数字。

注意:

你的算法应该一个线性时间复杂度完成。你能不能无需使用额外的内存来完成它

【思路一】

所有的数用二进制表示,我们把每个数的第i 位取和之后再对3取余,那么只会有两个结果 0 或 1 。  如果为0代表只出现一次的那个数第i位也为0,

如果为1表示只出现一次的那个数第i位也为1。因此取余的结果就是那个 “Single Number”。

下面是一个直接用大小为 32的数组来记录所有 位上的和。

【代码一】

/*---------------------------------------
*   日期:2015-04-26
*   作者:SJF0115
*   题目: 137.Single Number II
*   网址:https://leetcode.com/problems/single-number-ii/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int singleNumber(int A[], int n) {
        int count[32] = {0};
        int result = 0;
        for(int i = 0;i < 32;++i){
            for(int j = 0;j < n;++j){
                if ((A[j] >> i) & 1) {
                    ++count[i];
                }//if
            }//for
            result |= ((count[i] % 3) << i);
        }//for
        return result;
    }
};

int main(){
    Solution solution;
    int A[] = {2,3,4,2,5,2,3,3,5,5};
    int result = solution.singleNumber(A,10);
    // 输出
    cout<<result<<endl;
    return 0;
}

【思路二】

这个算法是有改进的空间的,可以使用掩码变量

方法 2:用 ones 记录到当前处理的元素为止,二进制 1 出现“1 次”(mod 3 之后的 1)的有哪些二进制位;

用 twos 记录到当前计算的变量为止,二进制 1 出现“2 次”(mod 3 之后的 2)的有哪些二进制位。

当 ones 和 twos 中的某一位同时为 1 时表示该二进制位上 1 出现了 3 次,此时需要清零。

即用二进制模拟三进制运算。最终 ones 记录的是最终结果。

【代码二】
/*---------------------------------------
*   日期:2015-04-26
*   作者:SJF0115
*   题目: 137.Single Number II
*   网址:https://leetcode.com/problems/single-number-ii/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int singleNumber(int A[], int n) {
        int ones = 0, twos = 0, threes = 0;
        for(int i = 0;i < n;++i){
            // 出现2次
            twos |= (ones & A[i]);
            // 出现1次
            ones ^= A[i];
            // 当ones和twos中的某一位同时为1时表示该二进制位上1出现了3次
            threes = ones & twos;
            // 二进制位上1出现了3次此时ones和twos对应位上清零
            ones &= ~threes;
            twos &= ~threes;
        }//for
        return ones;
    }
};

int main(){
    Solution solution;
    int A[] = {2,3,4,2,5,2,3,3,5,5};
    int result = solution.singleNumber(A,10);
    // 输出
    cout<<result<<endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值