【leetcode】Single Number 2

本文介绍了一种高效算法来找出数组中只出现一次的元素,该算法的时间复杂度为O(n),且不使用额外内存。通过利用位运算技巧,文章详细解释了如何在数组中统计每个元素出现的次数,并最终确定只出现一次的那个元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题:

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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int bits[32] = {0};
        for(int i=0 ; i<n ; i++){
            for(int j=0 ; j<32 ; j++){
                bits[j] = ((A[i]>>j) & 1 )+ bits[j];
                bits[j] = bits[j] % 3;
            }
        }
        int ret = 0;
        for(int i=31 ; i>=0 ; i--){
            ret = ret*2 + bits[i];
        }
        return ret;
    }
};
其中,最后的根据bits[]求ret。也可以用以下方法:

        for(int i=0 ; i<32 ; i++){
            ret = ((bits[i])<<i) + ret;
        }

或者(从位运算角度)

        for(int i=0 ; i<32 ; i++){
            ret = ((bits[i])<<i) | ret;
        }



总结:开始时不会做本题,参考网上其他人的解答后自己写的代码。主要思路是,用含32个元素的数组分别记录每位出现的1的次数(要么为1,要么为3的倍数),最后所有为1的各位组成的数即为所求。时间复杂度O(32n) = O(n),空间复杂度为O(32)=O(1)。

这种方法的可扩展性非常强,适用于本题的其他变种,如之前的Single Number。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值