首页 > 其他 > 详细

Single Number II

时间:2015-03-05 18:46:37      阅读:204      评论:0      收藏:0      [点我收藏+]

Single Number II 

问题:  

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?

思路:

  hashtable 容易想到

  bit vector 新思路

他人代码:

技术分享
public class Solution {
    public int singleNumber(int[] A) {
        /*
        element in A is 32bit,
        sum corresponding bits from all elements and mod each by 3 then should left the single number
        */
        int[] sum=new int[32];
        int res=0;
        for(int i=0;i<32;i++)
        {
            for(int j=0;j<A.length;j++)
            {
                sum[i]+=((A[j]>>i)&1);//sum every bit of all numbers
            }
            sum[i]%=3;
            res+=((sum[i]&1)<<i);// recover the single number
        }
        return res;
    }
}
View Code

学习之处:

  • bit vector 这种数据结构实在太美妙了
  • 右移 缩小2倍 左移 添加0 增大2倍 深刻左移和右移的含义
  • 数据的变换与恢复方法

Single Number II

原文:http://www.cnblogs.com/sunshisonghit/p/4316222.html

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