[leetcode] Single Number II

本文详细介绍了解决LeetCode中单数元素问题的三种算法,包括使用位运算、迭代位数计数和优化迭代位数计数的方法。每种算法都提供了时间复杂度为O(n)且空间复杂度为O(1)的解决方案。

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

From : https://leetcode.com/problems/single-number-ii/

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?

Solution 1:

class Solution {
public:
	int singleNumber(vector<int> nums) {
        int bitnum[32]={0};
        int res=0;
        for(int i=0; i<32; i++){
            for(int j=0, n=nums.size(); j<n; j++){
                bitnum[i]+=(nums[j]>>i)&1;
            }
            res|=(bitnum[i]%3)<<i;
        }
        return res;
    }
};

Solution 2:

class Solution2 {
public:
    int singleNumber(vector<int>& nums) {
		int ans = 0, posi;
		for(int i=0; i<32; i++) {
			posi = 0;
			for(int j=0, size=nums.size(); j<size; j++) {
				posi += (nums[j]>>i)&1;
			}
			ans |= (posi%3)<<i;
		}
        return ans;
    }
};

public class Solution {
    public int singleNumber(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int a = 0;
        for(int I=0; I<32; ++I) {
            int n = 0;
            int F = 1<<I;
            for(int i=0; i<nums.length; ++i) {
                if((nums[i]&F) != 0) { // 必须不等于0,>0 <0对于正负数的情况会出现错误
                    ++n;
                }
            }
            if(n%3 == 1) {
                a |= F;
            }
        }
        return a;
    }
}


Solution 3:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
		// ont %3为1的积累,two %3为2, three %3为0
        int one=0, two=0, three=0;
		for(int i=0, n=nums.size(); i<n; i++){
			// %3为1的积累和这次数的1,即%3为2的积累, 与上次积累%3为2的或为这次积累量
            two |= one & nums[i];
            // 这次与前一次%3为1的积累异或,为当前%3为1的积累
			one ^= nums[i];
            // %3为0的积累
			three = one & two;
            // 将出现三次的置为0
			one &= ~three;
            two &= ~three;
        }
        return one;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值