您的位置:首页 > 其它

leetcode:Single Number

2015-12-08 22:04 190 查看


转自:http://www.acmerblog.com/leetcode-solution-single-number-ii-6317.html


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

01
//
LeetCode, Single Number
02
//
时间复杂度O(n),空间复杂度O(1)
03
class
Solution
{
04
public
:
05
int
singleNumber(
int
A[],
int
n)
{
06
int
x
= 0;
07
for
(
size_t
i
= 0; i < n; ++i)
08
x
^= A[i];
09
return
x;
10
}
11
};
代码2

view source

1
//
LeetCode, Single Number
2
//
时间复杂度O(n),空间复杂度O(1)
3
class
Solution
{
4
public
:
5
int
singleNumber(
int
A[],
int
n)
{
6
return
accumulate(A,
A + n, 0, bit_xor<
int
>());
7
}
8
};


-------------------------------------------------------------------------------------------------


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

01
//
LeetCode, Single Number II
02
//
方法1,时间复杂度O(n),空间复杂度O(1)
03
class
Solution
{
04
public
:
05
int
singleNumber(
int
A[],
int
n)
{
06
const
int
W
=
sizeof
(
int
)
* 8;
//
一个整数的bit数,即整数字长
07
int
count[W];
//
count[i]表示在在i位出现的1的次数
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;
12
count[j]
%= 3;
13
}
14
}
15
int
result
= 0;
16
for
(
int
i
= 0; i < W; i++) {
17
result
+= (count[i] << i);
18
}
19
return
result;
20
}
21
};
代码2

view source

01
//
LeetCode, Single Number II
02
//
方法2,时间复杂度O(n),空间复杂度O(1)
03
class
Solution
{
04
public
:
05
int
singleNumber(
int
A[],
int
n)
{
06
int
one
= 0, two = 0, three = 0;
07
for
(
int
i
= 0; i < n; ++i) {
08
two
|= (one & A[i]);
09
one
^= A[i];
10
three
= ~(one & two);
11
one
&= three;
12
two
&= three;
13
}
14
15
return
one;
16
}
17
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: