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

LeetCode:Single Number II

时间:2014-07-22 00:28:38      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   strong   io   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?

 

这道题仍然用位运算来做,不过要比那道只用位异或来做的题要复杂得多。还是从数的二进制表示看起,假设数组大小为n,每个数由32位组成,分别把这n个数的第i位相加,然后%3,结果非0即1,结果为0时single one对应的位为0,结果为1时single one对应的位为1,最后返回32位的结果。

 

 1 class Solution {
 2 public:
 3     int singleNumber(int A[],int n){
 4         int bit=0,temp,i,j;
 5         if(n<0)
 6         {
 7             return -1;
 8         }
 9         for(i=0;i<32;i++)
10         {
11             temp=0;
12             for(j=0;j<n;j++)
13             {
14                 temp+=((A[j]>>i)&1);
15             }
16             bit|=((temp%3)<<i);
17         }
18         return bit;
19     }
20 };

LeetCode:Single Number II,布布扣,bubuko.com

LeetCode:Single Number II

标签:style   blog   color   strong   io   for   

原文地址:http://www.cnblogs.com/levicode/p/3858091.html

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