Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解析: 如果对所有元素做异或运算,其结果为那个出现一次的元素,理解是a1 ^ a2 ^ ....,可以将所有相同元素交换至相邻位置,首先运算相同元素,则会产生(n - 1)/2个0异或积,剩余一个单一元素,他们的异或积为这个单一元素自己,得解。
只要出现偶数次都可以参考。
class Solution {
public:
int singleNumber(int A[], int n) {
int x = A[0];
for (int i = 1; i < n ; ++i)
{
x ^= A[i];
}
return x;
}
};
2.
Single Number II
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的次数,这里是去除3个的,所以如果出现了三次,则可以去掉,剩下的就就是非三的那个数的有效位了,其他出现四次五次也可以这样。
class Solution {
public:
int singleNumber(int A[], int n) {
int M = sizeof(int) * 8;
int count[M];
fill_n(&count[0], M , 0);
for (int i = 0; i < n ; ++i)
{
for (int j = 0; j < M ; ++j)
{
count[j] += (A[i] >> j) & 1;
count[j] %= 3;
}
}
int result = 0;
for (int i = 0; i < M ; ++i)
{
result += count[i] << i;
}
return result;
}
};