137.Single Number II

本文介绍了一种算法,用于从整数数组中找出仅出现一次的数字,其余数字均出现三次。通过统计每位上所有元素的和并取余数来定位目标数字。

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

问题描述
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

解题思路
该问题给了我们一组数,其中只有一个数只出现了一次,其他的都出现了三次,要我们把只出现了一次的数找出来。我们可以这样思考,将数组中的每个数字用二进制表示,并且统计每一位上所有元素的和,除了只出现了一次的,其他的数都出现了三次,那么如果不包括我们要求的数,其他的数加起来在每一位上都是3的倍数,随意我们只要用每一位上的数字以3取余,就是我们要求的数在该位的值。最后在将二进制转为十进制即可。
代码展示

#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int count[32]={0};  
        int result=0;  
        for(int i=0;i<32;i++){  
            for(int j=0;j<nums.size();j++){  
                count[i]+=((nums[j]>>i)&1);   
                count[i]=count[i]%3;   
            }  
            result|=(count[i]<<i);  
        }  
        return result;  
    }
};
int main(){
    int n;
    vector<int> nums;
    cout<<"请输入向量长度:";
    cin>>n;
    int a;
    for(int i = 0;i<n;i++){
        cin>>a;
        nums.push_back(a);
    }

    Solution solution;
    int result=solution.singleNumber(nums);
    cout<<result<<endl;
}

运行结果
这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值