Single Number III
2016-04-07 18:49
190 查看
原文: Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. For example: Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. Note: The order of the result is not important. So in the above example, [5, 3] is also correct. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. Subscribe to see which companies asked this question 简单的点说,就是一个数组中有两个不一样的数不是成对出现的,其他的数都是成对出现的
public int[] singleNumber(int[] nums) { int mid = 0, index = 0, left = 0, right = 0; //计算数组中所有的数的异或的值,记为mid for(int i = 0, len = nums.length;i < len;i ++){ mid = mid ^ nums[i]; } //查找mid中最低位的1是第几位,记为index while((mid & (1 << index)) == 0){ index ++; } //根据数组中的数第index位是1或0的不同,进行划分为两部分,而这两部分正好有两个不同的数,其余的数都是成对出现的 for(int i = 0, len = nums.length;i < len;i ++){ if((nums[i] & (1 << index)) == 0){ left = left ^ nums[i]; }else{ right = right ^ nums[i]; } } return new int[]{left, right}; }
参考:
http://blog.csdn.net/morewindows/article/details/8214003
相关文章推荐
- 可爱的 HTTP Error 503。The service is unavailable
- 关于Office web apps的问题:写CheckFileInfo服务时遇到的问题
- Unity3D for VR 学习(4): 自绘摄像机的视口区域锥体
- 基于Spark上的中文分词算法的实现
- [POJ 2976] Dropping tests (二分答案)
- AppDelegate的生命周期
- 中国象棋人机对弈搜索算法学习-极大极小值,负极大值,alpha-beta算法
- (Caffe)基本类DataReader、QueuePair、Body(四)
- 线程同步的几种方式
- +(void)load与+(void)initialize
- Oracle字符串分割Split(超简单一条sql解决)
- CGOS461 [网络流24题] 餐巾(最小费用最大流)
- python-摩尔斯电码查询器
- 网页中嵌套百度地图
- PL/SQL Developer 中文字段显示乱码
- git 切换到远程分支
- 802.1x+AD+DHCP+NPS动态下发vlan Windows Server 2008端配置
- HBase高级特性:通过Coprocessor实现Solr Cloud二级索引
- stl -- 适配器
- python3.4 x86_64-linux-gnu-gcc Error