[Leetcode]Single Number II

来源:互联网 发布:高会军 争议 知乎 编辑:程序博客网 时间:2024/06/15 01:43

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?


class Solution {public:    /*algorithm: bit operation        just like binary op, count bit count and %3        time O(n) space O(1)    */    int singleNumber(vector<int>& nums) {        int bit[32]={0};        for(int i = 0;i < nums.size();i++){            int n = nums[i];            for(int k = 0;k < 32;k++){                bit[k] += n&0x1;                bit[k] %= 3;                n >>= 1;            }        }        int ret = 0;        for(int k = 0;k < 32;k++)            ret |= bit[k] << k;        return ret;    }};


0 0
原创粉丝点击