LintCode: Single Number II

一篇解析比较详细的文章:http://www.acmerblog.com/leetcode-single-number-ii-5394.html

C++

解法(1)

求出每个比特位的数目,然后%3,如果这个比特位只出现1次,那么这比特位就会余1,否则就会整除。

把每个余下的比特位求出来,就知道是哪个数只出现1次了。

 1 class Solution {
 2 public:
 3     /**
 4      * @param A : An integer array
 5      * @return : An integer 
 6      */
 7     int singleNumberII(vector<int> &A) {
 8         // write your code here
 9         int count[32] = {0};
10         int res = 0;
11         for (int i = 0; i < 32; i++) {
12             for (auto &v : A) {
13                 count[i] += (v >> i) & 1;
14             }
15             res |= ((count[i] % 3) << i);
16         }
17         return res;
18     }
19 };

解法(2)

表示看不懂。

原文地址:https://www.cnblogs.com/CheeseZH/p/5109720.html