码迷,mamicode.com
首页 > 其他好文 > 详细

Single Number II

时间:2019-06-24 00:38:42      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:return   com   with   appear   css   color   without   cto   line   

Given a non-empty 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?

Example 1:

Input: [2,2,3,2]
Output: 3
Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

code

class Solution
{
public:
    int singleNumber(vector<int>& nums)
    {
        if(nums.empty())
            return -1;
        else if(nums.size()==1)
            return nums.front();

        int res=0;
        for(int i=31;i>=0;--i)
        {
            int mask=1<<i;
            int count=0;
            for(int j=0;j<nums.size();++j)
                if(mask&nums.at(j))
                    ++count;
            if(count%3)
                res|=mask;
        }
        return res;
    }
};

 

Single Number II

标签:return   com   with   appear   css   color   without   cto   line   

原文地址:https://www.cnblogs.com/tianzeng/p/11074823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!