初阶。
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?
思路,使用异或,只要出现偶数次就可以清零。
class Solution{
public:
static int singleNum(int A[],int n)
{
int x = 0;
for(int i=0;i<n;i++)
{
x^=A[i];
}
return x;
}
};进阶。
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的整数倍,将所有这些1清零,剩下的就是最终的数。 用ones记录到当前计算的变量为止,二进制1出现“1次”(mod 3 之后的 1)的数位。用twos记录到当前计算的变量为止,二进制1出现“2次”(mod 3 之后的 2)的数位。当ones和twos中的某一位同时为1时表示二进制1出现3次,此时需要清零。即 用二进制模拟三进制计算 。最终ones记录的是最终结果。 时间复杂度: O(n)
博客围绕数组中查找唯一元素展开。初阶问题是数组中除一个元素外其他元素出现两次,可通过异或运算解决;进阶问题是除一个元素外其他元素出现三次,需考察位运算,且要求算法有线性时间复杂度,不使用额外内存。
714

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



