forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleNumber.II.cpp
29 lines (27 loc) · 1013 Bytes
/
singleNumber.II.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
// Source : https://oj.leetcode.com/problems/single-number-ii/
// Author : Hao Chen
// Date : 2014-06-17
/**********************************************************************************
*
* 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?
*
*
**********************************************************************************/
class Solution {
public:
int singleNumber(int A[], int n) {
int ones = 0, twos = 0, threes = 0;
for (int i = 0; i < n; i++) {
twos |= ones & A[i];
ones ^= A[i];// 异或3次 和 异或 1次的结果是一样的
//对于ones 和 twos 把出现了3次的位置设置为0 (取反之后1的位置为0)
threes = ones & twos;
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
};