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?
------------
class Solution {
public:
int singleNumber(int A[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int ones = 0, twos = 0, not_three = 0;
for (int i = 0; i < n; i++) {
int x = A[i];
twos |= ones & x;
ones ^= x;
not_three = ~(ones & twos);
ones &= not_three;
twos &= not_three;
}
return ones;
}
};
初始化 : ones包含只出现1次bit信息, twos包含所有出现两次的bit信息,not_three包含所有出现少于三次的bit信息
对数组中每个整数(x)进行以下操作:
1. twos |= ones & x -- 获得当前整数x与现有ones的交集,也就是出现两次的bit信息,把这些得到的出现两次的bit信息 或 到 twos上
2. ones ^= x, 分三种情况 : x出现1,2,3次, 除了出现两次外,ones将包含该数的bit信息
3. not_three = ~(ones & twos); 把当前非出现三次的bit信息赋值给 not_three
4. ones
&= not_three; 从ones里边清除出现三次的bit信息
5. twos &= not_three; 从twos清除出现三次的bit信息
本文介绍了一种线性时间复杂度的算法,用于在一个除了一个数字外其余都出现了三次的整数数组中找到那个仅出现一次的数字。算法通过巧妙地利用位运算实现了不使用额外内存的目标。
405

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



