首页 > 其他 > 详细

leetcode || 137、Single Number II

时间:2015-04-30 10:47:03      阅读:111      评论:0      收藏:0      [点我收藏+]

problem:

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?

Hide Tags
 Bit Manipulation
题意:一个数组中,只有一个元素出现一次,其他元素出现K次,(k为奇数3)

thinking:

(1)这道题适用于出现奇次的情形,解法是:对数组所有数的每一位出现1的次数进行统计,对K取余后,就为待求数在该位的位数(0或者1),

          再将2进制转换为10进制即可

(2)这道题我假设int为32位,有些机器不是32位。

code:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        string s;
        int a=0x0001;
        int count=0;
        for(int i=0;i<32;i++)
        {
            for(int j=0;j<nums.size();j++)
            {
                if((nums[j]&a)!=0)
                    count++;
            }
            s.push_back('0'+count%3);
            a=a<<1;
            count=0;
        }
        return reverse_string_to_int(s);
    }
protected:
    int reverse_string_to_int(string s)
    {
        int a=1;
        int ret=0;
        for(int i=0;i<s.size();i++)
        {
            ret+=(s.at(i)-'0')*a;
            a*=2;
        }
        return ret;
    }
};


leetcode || 137、Single Number II

原文:http://blog.csdn.net/hustyangju/article/details/45368745

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!