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
1:采用xor
int singleNumber(int A[], int n)
{
int once = 0;
int twice = 0;
int third = 0;
for(int i = 0; i < n; i++)
{
twice |= once & A[i];
once ^= A[i];
third = once & twice;
once &= ~third;
twice &= ~third;
}
return once;
}

本文介绍了一种线性时间复杂度的算法来找出数组中只出现一次的元素,该元素在数组中所有其他元素均出现了三次。通过使用位操作,特别是XOR操作实现此目的,并且在实现过程中不使用额外内存。
302

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



