LeetCode 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?

Solve it according to bits of different position, we thus need to verify the 32 bits.  (suppose it is a 32-bit machine)

int singleNumber(vector<int>& nums) {
    int target = 0;
    for(int i = 0; i <= 31; ++i) {
        int count = 0;
        for(int j = 0; j < nums.size(); ++j) {
            count = count + ((nums[j] >> i) & 0x1);
        }
        target = target | ((count % 3) << i);
    }
    return target;
}

Time Complexity is 32O(n). It can pass leetCode, not sure whether this is the most optimized solution though.

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