【leetcode刷题笔记】Single Number II
2024-09-04 14:21:49
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;
}
}
最新文章
- 如何区分Babel中的stage-0,stage-1,stage-2以及stage-3(一)
- 在 Visual Studio 中调试时映射调用堆栈上的方法
- 系统升级日记(2)- 升级到SharePoint Server 2013
- shell note
- 使用BlockingQueue的生产者消费者模式
- No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=armv7 armv7s)
- Max Sum (hdu 1003 简单DP水过)
- JSON数据传递
- Android 开发—— 小工具,大效率
- PHP面试题:HTTP中POST、GET、PUT、DELETE方式的区别
- ●UOJ 21 缩进优化
- 浅谈企业IT技术运营中台
- docker 删除所有退出的容器
- OpenStack安装-MySQL,Rabbitmq,memcache.
- 什么是servlet?
- Steeltoe之Service Discovery篇
- Win10系列:UWP界面布局进阶1
- spark基础知识介绍2
- VS2010/MFC编程入门之四十一(文档、视图和框架:分割窗口)
- android apk签名原理
热门文章
- Oracle基础学习登陆SQLPLUS(一)
- String类和StringBuilder
- PHP递归实现无限级分类
- Spectral Graph Theory的一些定理
- ios --也是在B页面的生命周期设置如下代码。方法一是直接关闭和激活侧滑手势,方法二则是B遵循协议UIGestureRecognizerDelegate,设置侧滑交互代理,重写手势方法。
- OpenCV学习笔记:opencv_ml模块
- Python将数据保存到CSV中
- tf.name_scope()和tf.variable_scope()
- HDU1688(Sightseeing)
- EasyNVR depends on ffmpeg,yasm/nasm not found or too old. Use --disable-yasm for a crippledbuild