Single Number III
2015-08-23 10:13
309 查看
Description:
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?
Code:
PS:
思路很清晰,但是写代码的是后老在细节出错,主要是两个判断条件要注意
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?
Code:
vector<int> singleNumber(vector<int>& nums) { vector<int>result; if (nums.size() < 2) return result; int xorAll = 0; for (int i = 0; i < nums.size(); ++i) xorAll^=nums[i]; unsigned int x = 1; while ((xorAll & x) == 0) { x=x<<1; } int result1=0,result2=0; for (int j = 0; j < nums.size(); ++j) { if ((nums[j]&x) == 0) result1^=nums[j]; else result2^=nums[j]; } result.push_back(result1); result.push_back(result2); return result; }
PS:
思路很清晰,但是写代码的是后老在细节出错,主要是两个判断条件要注意
相关文章推荐
- iOS学习UI之UIButton
- 日经春秋 20150823
- Leetcode: Binary Tree Paths
- BT5
- 减脂日记-8-23
- Spark SQL 源代码分析系列
- 洛谷1029 最大公约数和最小公倍数问题 解题报告
- 母版页的使用总结
- 天声人語 20150823
- Detect the Virus - ZOJ 3430(恶心的自动机)
- addChildViewController的用法
- 常用的日文正文字体有哪些?
- ASP.NET MVC 4 插件化架构简单实现-思路篇
- 每个Android开发者应该知道的6个SDK和API
- 《JavaScript高级程序设计》
- 洛谷1908 逆序对 解题报告
- jquery ajax 如何向jsp提交表单数据
- hdu 5418 Victor and World(floyd+状压dp)
- 黑马程序员-[OC]学习之旅-ARC机制和类别
- Ubuntu 安装keepalived