-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignal_number.cpp
More file actions
65 lines (50 loc) · 1.36 KB
/
signal_number.cpp
File metadata and controls
65 lines (50 loc) · 1.36 KB
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
58
59
60
61
62
63
64
/*
leetcode上一道题
2.1.24 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?
自己没想出来
参考别人的代码吧
用二进制模拟“三进制”,当二进制某一位上出现三次1时,将该位清零
*/
#include <vector>
#include <iostream>
using namespace std;
int singleNumber(vector<int>& nums)
{
int one = 0, two = 0, three = 0;
for (auto i : nums) {
two |= (one & i);
one ^= i;
three = ~(one & two);
one &= three;
two &= three;
}
return one;
}
//这个解法更容易理解一些
int singleNumber2(vector<int>& nums)
{
const int W = sizeof(int) * 8;
int count[W];//每个count[i]表示二进制一位
memset(count, 0, W * sizeof(int));
for (int i = 0; i < nums.size(); i++) {
for (int j = 0; j < W; j++) {
count[j] += (nums[i] >> j) & 1;
count[j] %= 3;
}
}
int result = 0;
for (int i = 0; i < W; i++) {
result += (count[i] << i);
}
return result;
}
int main()
{
int test[] = {10 ,5,4,10,5,4,10,5,4,9};
vector<int> t(test, test + 10);
int result = singleNumber2(t);
cout<<"result "<<result<<endl;
return 0;
}