Single Number III
2015-11-03 15:07
387 查看
题目:
Given an array of numbers
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?
分析:
这题没想出来
题目大意:一个数组,有两个元素出现了一次,其余元素都出现两次,让用线性时间复杂度和常量空间复杂度找出这两个数。
解题思路:考虑位操作,对所有元素做异或操作,那么最后得到的值就是要求的两个元素异或得到的,那么找出其中为1的某一位,说明这一位两个数一个为0,一个为1,以这一位为标准,把数组的元素分为两组A、B,那么要求的两个元素肯定是一个在A组,一个在B组,而对这两组各自做异或操作,就可以得到两个数就是要求的。
注意n&(~(n-1))表示取的n中的第一个为1的且其他置为0,(我也不知道为什么)
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?
分析:
这题没想出来
题目大意:一个数组,有两个元素出现了一次,其余元素都出现两次,让用线性时间复杂度和常量空间复杂度找出这两个数。
解题思路:考虑位操作,对所有元素做异或操作,那么最后得到的值就是要求的两个元素异或得到的,那么找出其中为1的某一位,说明这一位两个数一个为0,一个为1,以这一位为标准,把数组的元素分为两组A、B,那么要求的两个元素肯定是一个在A组,一个在B组,而对这两组各自做异或操作,就可以得到两个数就是要求的。
注意n&(~(n-1))表示取的n中的第一个为1的且其他置为0,(我也不知道为什么)
class Solution { public: vector<int> singleNumber(vector<int>& nums) { int len = nums.size(); int AxorB = 0; for(int i=0; i<len; i++){ AxorB ^= nums[i]; } int mask = AxorB & (~(AxorB-1)); int A = 0; int B = 0; for(int i=0; i<len; i++){ if((mask&nums[i])==0){ A ^= nums[i]; }else{ B ^= nums[i]; } } return vector<int>({A, B}); } };
相关文章推荐
- Windows下编译objective-C
- nginx如何利用ngx_channel_t在进程间传递消息
- MyBatis学习总结(七)——Mybatis缓存
- 游戏摇杆之Easy Touch 3教程
- python随机读取文件中的某一行内容
- java WEB项目打包部署到tomcat
- Web API应用架构设计分析(2)
- 深入浅出看流媒体前世今生,分分钟二逼变牛逼
- 用apache-cxf生成webservice客户端的时候报错Parameter: shead already exists for method
- 求数组最大值、求和、乘法表、取整
- No change while using CSS <form target="blank">
- 非root用户启动tomcat
- jenkins配置应用自动部署到docker
- Sublime2 for Mac OSX配置(Python developer)
- Sublime2 for Mac OSX配置(Python developer)
- matlab 位操作
- Web API应用架构设计分析(1)
- Android播放器, ffmpeg源码添加打印,在logcat显示
- [MySQL FAQ]系列 — 如何安全地关闭MySQL实例
- Java开发中的23种设计模式详解(转)