LeetCode260——Single Number III精彩解法
2015-10-01 00:02
337 查看
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:
实现:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int ax = 0;
int a=0, b = 0;
for (int item : nums) {
ax ^= item;
}
int lastb = (ax & (ax-1)) ^ ax;
for (int item : nums) {
if (item & lastb) {
a ^= item;
} else {
b ^= item;
}
}
return vector<int>{a, b};
}
};
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:
实现:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int ax = 0;
int a=0, b = 0;
for (int item : nums) {
ax ^= item;
}
int lastb = (ax & (ax-1)) ^ ax;
for (int item : nums) {
if (item & lastb) {
a ^= item;
} else {
b ^= item;
}
}
return vector<int>{a, b};
}
};
相关文章推荐
- 一个关于if else容易迷惑的问题
- 一道sql面试题附答案
- C# 超高面试题收集整理
- 人人网javascript面试题 可以提前实现下
- PHP中设置一个严格30分钟过期Session面试题的4种答案
- 据说是雅虎的一份PHP面试题附答案
- php牛逼的面试题分享
- 一套比较完整的javascript面试题(部分答案)
- 小米公司JavaScript面试题
- 超级全面的PHP面试题整理集合第1/2页
- 5个实用的shell脚本面试题和答案
- PHP经典面试题集锦
- 8个PHP数组面试题
- PHP中提问频率最高的11个面试题和答案
- 用PHP解决的一个栈的面试题
- 几道坑人的PHP面试题 试试看看你会不会也中招
- 5个JavaScript经典面试题
- Java高级面试题小结
- Java实现栈和队列面试题
- JAVA实现链表面试题