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

[LeetCode] Single Number II

时间:2014-07-07 22:57:13      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   strong   width   for   

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?

 

方法一:创建一个长度为 多少个bit/sizeof(int) * 8的数组 count[sizeof(int)*8],count[i] 表示在在 i 位
出现的 1 的次数。如果 count[i] 是 3 的整数倍,则忽略;否则就把该位取出来组成答案。

 

 1 class Solution
 2 {
 3     public:
 4         int singleNumber(int A[], int n)
 5         {
 6             vector<int> cnt;
 7             int width = sizeof(int)*8;
 8             cnt.resize(width, 0);
 9             int res = 0;
10 
11             for(int i  = 0; i< n; i++)
12             {
13                 for(int j  = 0; j< width; j++)
14                 {
15                     cnt[j] += (A[i] >> j) & 0x1;
16                     //cnt[j] %= 3;
17                 }
18 
19             }
20             for(int j  = 0; j< width; j++)
21             {
22                 //cout << "j :\t" <<j <<"\t cnt\t"<< cnt[j]<<endl;
23                 if(cnt[j]%3 != 0)
24                     res ^=  ( 1 << j);
25             }
26             return res;
27         }
28 } ;

 

[LeetCode] Single Number II,布布扣,bubuko.com

[LeetCode] Single Number II

标签:style   blog   color   strong   width   for   

原文地址:http://www.cnblogs.com/diegodu/p/3812826.html

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