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

【Single Num II】cpp

时间:2015-04-27 21:25:23      阅读:116      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!