【Leetcode】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?

分析:可以设置一个size(int)的数组count,依次检查原有数组中的每个数,将其转换为二进制,将对应的为1的位置在count数组中做记录。count[i]的第i个元素则表示在第i位出现的1的次数。

class Solution {
public:
    int singleNumber(int A[], int n) {
        int count[32];
        for(int i = 0; i != 32; i++)
            count[i] = 0;
        
        for(int i = 0; i != n; i++)
            for(int j = 0; j != 32; j++)
                count[j] += (A[i] >> j) & 1;
        
        int result = 0;
        for (int i = 0; i < 32; i++) 
        {
            count[i] %= 3;
            result += (count[i] << i);
        }
        
        return result;
    }
};


你可能感兴趣的:(【Leetcode】Single Number II)