解题思路:
转自题目后面讨论区 用两个数字来维护提交代码:维护map
class Solution {
public int singleNumber(int[] nums) {
int x1=0,x2=0;
for(int num : nums) {
x1=(x1^num)&~x2;
x2=(x2^num)&~x1;
}
return x1;
}
}
运行结果:

本文介绍了一种使用两个数字变量x1和x2维护并找出数组中唯一出现一次的数字的方法。通过位运算实现,避免了使用额外的数据结构,如map。此算法适用于面试或竞赛中的快速解题。
提交代码:维护map
class Solution {
public int singleNumber(int[] nums) {
int x1=0,x2=0;
for(int num : nums) {
x1=(x1^num)&~x2;
x2=(x2^num)&~x1;
}
return x1;
}
}
运行结果:


被折叠的 条评论
为什么被折叠?