数组中出现一次的两个数 leetcode Single Number III
2015-09-09 11:28
357 查看
Given an array of numbers
once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given
Note:
The order of the result is not important. So in the above example,
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
解题思路:有一个数组,其中只有两个数出现一次,其他数均出现两次,求出这两个数。参考signal number的第二种解法:http://blog.csdn.net/sinat_24520925/article/details/45576735
我们将这个数组分成两个数组,每个数组中都只有一个元素出现一次。也就是先异或所有元素,得到resultExclusive,找到resultExclusive中二进制表示的由右向左的第一位1,则表明数组中有一个一次出现的数该位的值不同,一个为0、另一个为0.下面就好做了,将数组中该位均为0的异或,均为1的异或就可求得只出现一次的那两个数。
代码如下:
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?
解题思路:有一个数组,其中只有两个数出现一次,其他数均出现两次,求出这两个数。参考signal number的第二种解法:http://blog.csdn.net/sinat_24520925/article/details/45576735
我们将这个数组分成两个数组,每个数组中都只有一个元素出现一次。也就是先异或所有元素,得到resultExclusive,找到resultExclusive中二进制表示的由右向左的第一位1,则表明数组中有一个一次出现的数该位的值不同,一个为0、另一个为0.下面就好做了,将数组中该位均为0的异或,均为1的异或就可求得只出现一次的那两个数。
代码如下:
class Solution { public: vector<int> singleNumber(vector<int>& nums) { vector<int> res; if(nums.size()==0) return res; res.push_back(0); res.push_back(0); int resultExclusive=0; for(int i=0;i<nums.size();i++) resultExclusive^=nums[i]; int indexof1=0; while(((resultExclusive&1)==0)&&(indexof1<8*sizeof(int))) { resultExclusive=resultExclusive>>1; ++indexof1; } for(int i=0;i<nums.size();i++) { if((nums[i]>>indexof1)&1==1) res[0]^=nums[i]; else res[1]^=nums[i]; } return res; } };值得注意的是::
(resultExclusive&1)==0)
(resultExclusive&1)一定要加(),否则因为==的优先级高于&,会导致while循环无法进入!!!!
相关文章推荐
- Markdown 扩展语法 & 不同
- linux 系统监控命令 vmstat
- 从一张表里插入到另一张表
- [大数据处理]-如何用消息系统避免分布式事务?
- centos7 PHP5.6.13升级
- Hdu 1166 线段树的运用
- GTS Fail修改集锦com.google.android.xts.afw.AfwRequiredAppsOverlaysTest
- Linux进程理解与实践(一)基本概念和编程概述(fork,vfork,cow)
- Android的BUG(三) - 广为人知的诟病:频繁重启问题
- jdbc连接数据库失败,com.microsoft.sqlserver.jdbc.SQLServerException: 到主机 的 TCP/IP 连接失败。
- Maven的pom.xml配置文件详解
- abap普通屏幕使用tablecontrol时双向数据传递描述
- 获取指定路径下的所有图片文件名
- linux 系统监控命令 vmstat
- Web打印连续的表格,自动根据行高分页
- CascadeType属性说明
- 用JAVA把JSON字符串转成JSON格式化的字符串 - tooyond
- 【拾遗】C++申请与销毁动态二维数组
- 解决“您当前无权访问该文件夹”的问题
- C++类中静态变量和普通变量的区别