-
Notifications
You must be signed in to change notification settings - Fork 0
/
Single_Number.cpp
57 lines (56 loc) · 1.51 KB
/
Single_Number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//////////////////////////////////////////////////////
// Project: MyLeetCode
//
// Author: YanShicong
// Date: 2014/11/14
//////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------------------------------
* 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?
//--------------------------------------------------------------------------------------------------------------*/
#include "../include/include.h"
// 异或操作可以清除偶数次出现的情况
// 时间复杂度O(n),空间复杂度O(1)。
#define W2
#ifdef W1
// Use STL
class Solution {
public:
int singleNumber(int A[], int n) {
#if __cplusplus < 201103L
int sum(0);
for_each(A, A+n, [&](int n){sum ^= n;});
return sum;
#else
return accumulate(A, A+n, 0, bit_xor<int>());
#endif
}
};
#endif
#ifdef W2
// Not Using STL
class Solution {
public:
int singleNumber(int A[], int n) {
int result(0);
for (int i = 0; i < n; ++i)
{
result ^= A[i];
}
return result;
}
};
#endif
//--------------------------------------------------------------------------------------------------------------
TEST_CASE("Single_Number", "[Arrays]"){
Solution s;
SECTION("Empty Input"){
REQUIRE(s.singleNumber(NULL, 0) == 0);
}
SECTION("Normal Input"){
int A[5] = {1,1,1,2,2};
REQUIRE(s.singleNumber(A,5) == 1);
}
}