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?
复杂度O(n),不能用其他辅助空间,之前做过类似的题,用异或位操作,偶数次的数异或为0,最后的数就是所求的数。
class Solution {
public:
int singleNumber(int A[], int n) {
int s = 0;
for(int i = 0;i<n;i++)
{
s = s^A[i];
}
return s;
}
};
进阶版
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?
一个数组里只有一个数不出现3次,复杂度O(n),不能用辅助空间,并不会。。。又长见识了
class Solution {
public:
int singleNumber(int A[], int n) {
int ones = 0;//记录只出现过1次的bits
int twos = 0;//记录只出现过2次的bits
int threes;
for(int i = 0; i < n; i++){
int t = A[i];
twos |= ones&t;//要在更新ones前面更新twos
ones ^= t;
threes = ones&twos;//ones和twos中都为1即出现了3次
ones &= ~threes;//抹去出现了3次的bits
twos &= ~threes;
}
return ones;
}
};