137. 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?
Analysis:
参考:http://www.acmerblog.com/leetcode-single-number-ii-5394.html
只写了一个中等方法,但更容易理解,普适性更强些。
Source Code(C++):

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        if (nums.size()<1) {
// return ;
        }
        int bit_nums=0, res=0;
        for(int i=0; i<32; i++) {
            for (int j=0; j<nums.size(); j++) {
                if (((nums.at(j)>>i)&1) == 1) {
                    bit_nums++;
                }
            }
            res |= (bit_nums%3)<<i;
            bit_nums=0;
        }
        return res;
    }
};

int main() {
    vector<int> v;
    v.push_back(5);
    v.push_back(5);
    v.push_back(5);
    v.push_back(10000);
    Solution sol;
    cout << sol.singleNumber(v);
    return 0;
}

你可能感兴趣的:(137. Single Number II)