Given an array of integers, every element appears three times except for one. Find that single one.
public class Solution {
public int singleNumber(int[] A) {
int ones=0,twos=0,threes=0;
for(int i=0;i<A.length;i++){
twos|=ones&A[i];
ones^=A[i];
threes=ones&twos;
ones&=~threes;
twos&=~threes;
}
return ones!=0?ones:twos;
}
}
Given an array of integers, every element appears twice except for one. Find that single one.
public class Solution {
public int singleNumber(int[] A) {
int ones=0;
for(int i=0;i<A.length;i++){
ones^=A[i];
}
return ones;
}
}
本文提供了两种情况下查找数组中唯一不重复元素的方法:一种是在所有元素都出现三次的情况下找到仅出现一次的元素;另一种是在所有元素都出现两次的情况下找到仅出现一次的元素。通过位操作实现了高效解决方案。

437

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



