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?


题解:线性时间,O(1)的空间复杂度,只能把整数写成二进制的形式运算了。具体做法如下:

比如有一个数组{5,5,5,3,2,3,3},这些数写成二进制如下:

5:101

5:101

5:101

3:011

2:010

3:011

3:011

我们分别统计这三位的1的个数,然后对3取模,得到每一位的结果结合起来就是010,就是只出现一次的数字2.

所以,我们可以设置一个32位的数组,然后对A中的所有数字,统计这32位中每一位上1的个数,然后对3取模,最后得到的32位的二进制数就是只出现一次的那个数了。

Java代码如下:

 public class Solution {
public int singleNumber(int[] A) {
int[] digits = new int[32];
for(int i = 0;i < 32;i++){
for(int j = 0;j < A.length;j++){
digits[i] += (A[j] >> i)&1;
}
}
int result = 0;
for(int i = 0;i < 32;i++){
result += (digits[i]%3) << i;
}
return result;
}
}

最新文章

  1. 如何区分Babel中的stage-0,stage-1,stage-2以及stage-3(一)
  2. 在 Visual Studio 中调试时映射调用堆栈上的方法
  3. 系统升级日记(2)- 升级到SharePoint Server 2013
  4. shell note
  5. 使用BlockingQueue的生产者消费者模式
  6. No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=armv7 armv7s)
  7. Max Sum (hdu 1003 简单DP水过)
  8. JSON数据传递
  9. Android 开发—— 小工具,大效率
  10. PHP面试题:HTTP中POST、GET、PUT、DELETE方式的区别
  11. ●UOJ 21 缩进优化
  12. 浅谈企业IT技术运营中台
  13. docker 删除所有退出的容器
  14. OpenStack安装-MySQL,Rabbitmq,memcache.
  15. 什么是servlet?
  16. Steeltoe之Service Discovery篇
  17. Win10系列:UWP界面布局进阶1
  18. spark基础知识介绍2
  19. VS2010/MFC编程入门之四十一(文档、视图和框架:分割窗口)
  20. android apk签名原理

热门文章

  1. Oracle基础学习登陆SQLPLUS(一)
  2. String类和StringBuilder
  3. PHP递归实现无限级分类
  4. Spectral Graph Theory的一些定理
  5. ios --也是在B页面的生命周期设置如下代码。方法一是直接关闭和激活侧滑手势,方法二则是B遵循协议UIGestureRecognizerDelegate,设置侧滑交互代理,重写手势方法。
  6. OpenCV学习笔记:opencv_ml模块
  7. Python将数据保存到CSV中
  8. tf.name_scope()和tf.variable_scope()
  9. HDU1688(Sightseeing)
  10. EasyNVR depends on ffmpeg,yasm/nasm not found or too old. Use --disable-yasm for a crippledbuild