LeetCode 题解(23): 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?


题解:

完全不用存储空间的解法做不到,请高人指点。只能做到用一个int的存储空间了。按位统计每一位1出现的次数,该次数模3只可能有两种结果0或者1,1即来自于单独的那个数。

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


你可能感兴趣的:(Algorithm,LeetCode,number,single,II)