class Solution {
public int trainingPlan(int[] actions) {
int one = 0;
int two = 0;
for (int ac : actions) {
one = one ^ ac & ~two;
two = two ^ ac & ~one;
}
return one;
}
}
class Solution {
public int trainingPlan(int[] actions) {
Map<Integer,Integer> map=new HashMap<>();
for(int n:actions){
int data=map.getOrDefault(n, 0);
if(data==0) map.put(n,1);
else map.put(n,data+1);
}
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
if(entry.getValue()==1)
return entry.getKey();
}
return 0;
}
}
On On
位运算
public int singleNumber(int[] nums) {
int a = 0, b = 0;
for (int c : nums) {
// 尝试不同的表达式组合
int tempa = (~a & b & c) | (a & ~b & ~c);
b = (~a & ~b & c) | (~a & b & ~c);
a = tempa;
}
return b;
}
// 遍历数组中的每个数字
for (int num : actions) {
for (int i = 0; i < 32; i++) {
// 统计 num 的第 i 位是否为 1
bitCounts[i] += (num >> i) & 1;
}
}
// 通过模 3 恢复教练的编号
int result = 0;
for (int i = 0; i < 32; i++) {
if (bitCounts[i] % 3 != 0) {
result |= (1 << i); // 将第 i 位加入到结果中
}
}
return result;
class Solution {
public int trainingPlan(int[] actions) {
int m = 1, ans = 0;
int[] res = new int[32];
for (int i = 0; i < 32; i++) {
// 统计每一位
for (int action : actions) {
if ((action & m) != 0) {
res[i] += 1;
}
}
// 取余3消除出现三次的数
res[i] = res[i] % 3;
ans += res[i] * m;
m = m << 1;
}
return ans;
}
}
共以下 11 个回答
时间复杂度O(n)
空间复杂度O(1)
解题思路
– 数组中每个元素的二进制数,按倒数第1位,第2位…的顺序按位相加,相加结果%3=1,说明单独出现的数字第i位也是1
【题解1】
思路:膜拜了 状态机写法 过于复杂。遂练习Map 代码
方法一,看不懂位运算
On On
位运算
On O1
统计各个元素二进制位的出现次数,对3取余数,若为0则说明出现了3次,若为1则说明出现了1次。因为有三种状态,所以分别用00,01,10来表示。定义第一位为one,第二位为two。对于第一位,可以发现变化规律为0->1->0->0;第二位变化规律为0->0->1->0;只有循序不同,规律相同,因此可以用同一个公式表达。遍历数组计算one跟two的数值。因为数组中只有出现三次跟一次两种状态,所以只有00,01两种,two恒为0,最后one即为结果。
时间复杂度O(N),空间复杂度O(1)。
// 用来统计每个位上1的出现次数
int[] bitCounts = new int[32];
class Solution {
public int trainingPlan(int[] actions) {
int[] k = new int[32];
for(int i = 0; i < actions.length; i++){
for(int j = 0; j < 32; j++){
k[j] += (actions[i] >> j & 1) 1 ? 1 : 0;
}
}
int res = 0;
for(int i = 31; i >= 0; i–){
res = res << 1;
if(k[i] % 3 1){
res = (res | 1);
}
}
return res;
}
}
思路:统计每一位出现的次数,超过三次的最后记录下来就是答案
时间:O(n)
空间:O(1)
思路:位运算 | 逐位相加,对 3 取余。
时间复杂度:O(n)
空间复杂度:O(1)