给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,3,2]
输出: 3
示例 2:
输入: [0,1,0,1,0,1,99]
输出: 99
和上一题的异或思路一样,出现一次标记为1,出现两次标记为2,出现三次抵消掉。然后返回标记为1 的数字
三个标记值
twos |= ones & num; // twos 与 上一个 ones 有关
ones ^= num; //更新 ones
threes = ones & twos; //更新 threes
ones &= ~threes; //去掉 threes
twos &= ~threes;//去掉thress
class Solution {
public int singleNumber(int[] nums) {
int ones = 0, twos = 0, threes = 0;
for(int num : nums){
twos |= ones & num;
ones ^= num;
threes = ones & twos;
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
}
class Solution {
public int singleNumber(int[] nums) {
int ones = 0, twos = 0;
for(int num : nums){
ones = ones ^ num & ~twos;
twos = twos ^ num & ~ones;
}
return ones;
}
}