首页 > 其他 > 详细

【Single Num II】cpp

时间:2015-04-27 21:23:38      阅读:174      评论:0      收藏:0      [点我收藏+]

题目

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:
    int singleNumber(vector<int>& nums) {
            int result = 0;
            const int W = sizeof(int)*8;
            int *count = new int[W]();
            for (size_t i = 0; i < nums.size(); ++i)
            {
                for (size_t j = 0; j < W; ++j)
                {
                    count[j] += (nums[i] >> j) & 1;
                }
            }
            for (size_t i = 0; i < W; ++i)
            {
                if ( count[i]%3!=0 ) 
                {
                    result += ( 1 << i);
                } 
            }
            delete []count;
            return result;
    }
};

 

Tips:

1. 算法原理:由于都是int型的,只需要记录每个bit上1出现的次数;如果1出现的次数不是3的倍数,则将该位置置为1,并赋值到result中。

这道题主要是熟悉下位运算的各种操作,有时巧用位运算,可以大大提升代码效率。

【Single Num II】cpp

原文:http://www.cnblogs.com/xbf9xbf/p/4461286.html

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