137. Single Number II

来源:互联网 发布:极简主义 知乎 编辑:程序博客网 时间:2024/06/05 03:27

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?

class Solution {public:    int singleNumber(vector<int>& nums) {        int bits[32] = {0};        for(int num : nums){            int temp = num,index = 31;            // while(temp){            //     bits[index--] += temp & 1;            //     temp = temp >> 1;            // }            for(int i = 0; i < 32; i ++){                if(temp << i & (1 << 31))                    bits[i] += 1;            }                    }        int num = 0;        for(int i = 0; i < 32; i ++){            bits[i] = bits[i] % 3;            if(bits[i] != 0)                num |= 1 << (31 - i);        }        return num;    }};


原创粉丝点击