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?
标签: Hash Table Bit Manipulation
分析
异或,不仅能处理两次的情况,只要出现偶数次,都可以清零。
代码1
05 | int singleNumber( int A[], int n) { |
07 | for ( size_t i = 0; i < n; ++i) |
代码2
5 | int singleNumber( int A[], int n) { |
6 | return accumulate(A, A + n, 0, bit_xor< int >()); |
-------------------------------------------------------------------------------------------------
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?
标签: Bit Manipulation
分析
本题和上一题 Single Number,考察的是位运算。只有一个元素只出现了一次
方法1:创建一个长度为{sizeof(int)}的数组{count[sizeof(int)]},{count[i]}表示在在$i$位出现的1的次数。如果{count[i]}是3的整数倍,则忽略;否则就把该位取出来组成答案。
方法2:用{one}记录到当前处理的元素为止,二进制1出现“1次”(mod 3 之后的 1)的有哪些二进制位;用{two}记录到当前计算的变量为止,二进制1出现“2次”(mod 3 之后的 2)的有哪些二进制位。当{one}和{two}中的某一位同时为1时表示该二进制位上1出现了3次,此时需要清零。即\textbf{用二进制模拟三进制运算}。最终{one}记录的是最终结果。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ret=0;
int flg[sizeof(int)*8];
fill_n(&flg[0], sizeof(int)*8, 0);//要初始化为0!!
for(int i=0;i<nums.size();i++)
{
for(int j=0; j<sizeof(int)*8; j++)
{
flg[j] += ( (nums[i]>>j) & 1 );// 累计j位上1的个数
flg[j]%=3;//清零操作
}
}
for(int j=0; j<sizeof(int)*8; j++)
{
ret += (flg[j]<< j) ;//flg中元素要么是1,要么是0;nums只有一个元素值出现过一次
}
return ret;
}
};
代码1
05 | int singleNumber( int A[], int n) { |
06 | const int W = sizeof ( int ) * 8; |
08 | fill_n(&count[0], W, 0); |
09 | for ( int i = 0; i < n; i++) { |
10 | for ( int j = 0; j < W; j++) { |
11 | count[j] += (A[i] >> j) & 1; |
16 | for ( int i = 0; i < W; i++) { |
17 | result += (count[i] << i); |
代码2
05 | int singleNumber( int A[], int n) { |
06 | int one = 0, two = 0, three = 0; |
07 | for ( int i = 0; i < n; ++i) { |