Single Number II

来源:互联网 发布:帝国时代2征服者mac版 编辑:程序博客网 时间:2024/06/06 12:44

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

思路:用一个32位整数记录数组中所有元素每一位1的个数,元素出现三次模3为0,元素只出现一次模3为1

例:2 2 2 3 3 3 4
其中第一位为1的总数3,%3=0
第二位为1的总数为6,%3=0
第三位为1的总数1,%3=1

所以res=000…..00 00000100=4

int singleNumber(vector<int>& nums) {        int res = 0;        for (int i = 0; i < 32; ++i) {            int sum = 0;            for (int j = 0; j < nums.size(); ++j) {                sum += (nums[j] >> i) & 1;            }            res |= (sum % 3) << i;        }        return res;    }