第68题 Single Number II

本文介绍如何在数组中找到仅出现一次的整数,每个其他整数都出现了三次。利用位操作解决该问题,确保算法具有线性时间复杂度且不使用额外内存。

摘要生成于 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?

Hide Tags
  Bit Manipulation








Solution in C++ 1:
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        if(nums.size()==0) return 0;
        int one=0, two=0, three=0;
        for(int i=0; i<nums.size(); i++){
            two |= one&nums[i];
            one ^= nums[i];
            three = one&two;
            
            two &= ~three;
            one &= ~three;
        }
        return one;
    }
};
按比特求逻辑关系,注意2要放在1前面,否则会被1的新值影响。

Solution in C++ 2:
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        if(nums.size()==0) return 0;
        int solu[32];   //int值共有32位来储存
        memset(solu, 0, sizeof(solu));
        for(int i=0; i<nums.size(); i++){
            for(int index=0; index<32; index++){
               if ((nums[i]>>index)&1)  
                {  
                    solu[index]++;  
                }  
            }
        }
        int result=0;
        for(int i=0; i<32; i++){
            result += (solu[i]%3<<i);
        }
        return result;
    }
};

Note: 

这里我们需要重新思考,计算机是怎么存储数字的。考虑全部用二进制表示,如果我们把 第 ith  个位置上所有数字的和对3取余,那么只会有两个结果 0 或 1 (根据题意,3个0或3个1相加余数都为0).  因此取余的结果就是那个 “Single Number”.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值