[leetcode 260]Single Number III
2015-08-31 15:42
435 查看
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test
cases.
位运算,因为有两个元素不同,所以所有元素异或以后肯定不会为0,至少有一位为1。
找到第几位为一,异或操作分别找到两个数字
AC代码:
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.
位运算,因为有两个元素不同,所以所有元素异或以后肯定不会为0,至少有一位为1。
找到第几位为一,异或操作分别找到两个数字
AC代码:
class Solution { public: vector<int> singleNumber(vector<int>& nums) { vector<int> res; int sum=nums.size(); if(sum==0) return res; if(sum<=2) return nums; int temp=nums[0]; for(int i=1;i<sum;++i) temp^=nums[i]; int count=0; while(1) { if(temp&1==1) break; else { temp>>=1; ++count; } } int res1=0; int res2=0; for(int i=0;i<sum;++i) { if((nums[i]>>count)&1==1) res1^=nums[i]; else res2^=nums[i]; } res.push_back(res1); res.push_back(res2); return res; } };
其他Leetcode题目AC代码:https://github.com/PoughER/leetcode
相关文章推荐
- 阿福札记:正确的人
- mybits like查询写法
- 为什么TLF中setup和hold可以为负值
- redis php
- 【iScroll源码学习01】准备阶段 - 叶小钗
- 获取GridView的BoundField值
- 推荐一个golang的json库
- 在JavaScript遇到的坑(二)
- jQuery实现灰蓝风格标准二级下拉菜单效果代码
- awk的用法
- 关于datebase,cursor的一些异常 android.database.CursorWindowAllocationException: Cursor window allocation of
- linux下yum命令出现Loaded plugins: fastestmirror
- 常用正则表达式 -
- 【iScroll源码学习00】模拟iScroll
- C# 16进制转 Brush 颜色对象
- Useful Connection
- Python之yield
- Linux yum使用
- linux之nginx优化之自身优化
- SharedPreferences与Properties对比