It can be done in O(n) time and O(1) space.
Here is how you can do it with constant space in C#. I'm using the idea of "xor except with 3-state bits". For every set bit, the "xor" operation increments the corresponding 3-state value.
The final output will be the number whose binary representation has 1s in places that are either 1 or 2 in the final value.
void Main() {
Console.WriteLine (FindNonTriple(new uint[]
{1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3} ));
// 1
Console.WriteLine (FindNonTriple(new uint[]
{3, 2, 1, 3, 2, 1, 3, 2, 1, 4, 4, 4, 4} ));
// 4
}
uint FindNonTriple(uint[] args) {
byte[] occurred = new byte[32];
foreach (uint val in args) {
for (int i = 0; i < 32; i++) {
occurred[i] = (byte)((occurred[i] + (val >> i & 1)) % 3);
}
}
uint result = 0;
for (int i = 0; i < 32; i++) {
if (occurred[i] != 0) result |= 1u << i;
}
return result;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…