【leetcode】【137】Single Number II

探讨了在每个元素都出现三次的整数数组中找到仅出现一次的整数的方法。利用位运算特性,通过跟踪每个比特位上的1出现次数来解决此问题,确保线性时间复杂度且不使用额外内存。

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

1.问题描述

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?

2.问题分析

这个题与Single Number 是一个系列的,都是进行的位运算。但是问题I只需要进行异或操作就可以完成,但这个题显然没有这么简单。我参考了Discuss 点击打开链接,里面的分析还是非常有用的我贴出主要的
In Single Number, it is easy to think of XOR solution because XOR manipulation has such properties:

Commutative: A^B == B^A, this means XOR applies to unsorted arrays just like sorted. (1^2^1^2==1^1^2^2)
Circular: A^B^...^B == A where the count of B's is a multiple of 2.
So, if we apply XOR to a preceding zero and then an array of numbers, every number that appears twice will have no effect on the final result. Suppose there is a number H which appears just once, the final XOR result will be 0^H^...H where H appears as many as in input array.

When it comes to Single Number II (every one occurs K=3 times except one occurs M times, where M is not a multiple of K), we need a substitute of XOR (notated as @) which satisfies:

Commutative: A@B == B@A.
Circular: A@B@...@B == A where the count of B's is a multiple of K.
We need to MAKE the @ operation. This general solution suggests that we maintain a state for each bit, where the state corresponds to how many '1's have appeared on that bit, so we need a int[32] array.
这可以从本质上解决这类题,但是链接里的第一个回答,我还是没有弄明白 大哭

3.Java AC代码

public int singleNumber(int[] nums) {
        int k = 3;
		int res = 0;
		int[] bitCount = new int[32];
		for (int i = 0; i < bitCount.length; i++) {
			bitCount[i] = 0;
		}
		for (int i = 0; i < nums.length; i++) {
			int tmp = nums[i];
			for (int j = 0; j < bitCount.length; j++) {
				int hasBit = tmp & (1 << j);
				if (hasBit != 0) {
					bitCount[j] = (bitCount[j] + 1) % k;
				}

			}
		}
		for (int i = 0; i < bitCount.length; i++) {
			if (bitCount[i] > 0) {
				res |= (1 << i);
			}
		}
		return res;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值