leetcode 260 : Single Number III
2015-10-28 15:45
513 查看
(1、原题如下:
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?
2、解题如下:
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?
2、解题如下:
class Solution { public: vector<int> singleNumber(vector<int>& nums) { int a=0,b=0; for(int i:nums) a^=i;//利用xor找出两个数,形式为类似3^5 for(int i:nums) if(i&a&-a) b^=i;//判断条件非常关键,继续遍历,然后由于xor的特性,利用a&-a的技巧,先写出一个1,然后尾位为1(这里尾位定义为最后一个为1的位)的还是会被两次异或刷掉,因为留下的两个数必然有一个是有尾位而另一个没有(想想为什么),b被找出来后,另一个也就被找出来了 return {a^b,b}; } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 只有程序员看的懂的面试圣经|如何拿下编程面试
- 下一次技术面试时要问的 3 个重要问题
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- PHP程序员面试 切忌急功近利(更需要注重以后的发展)
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例