Leetcode: Single Number III
2015-10-17 11:50
393 查看
题目:
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?
分析:
两个相等的数异或结果为0。因此,首次扫描数组,得到两个单独的数a、b的异或结果axorb。因为a和b不相等,因此axorb一定不为0,且二进制位为1的位a和b一定不同。任取axorb中的一个不为0的二进制位,可以将原数组元素分成两组异或即得结果。
注:n & (-n)为n从低位向高位,第一个非0位所对应的数字
参考代码:
class Solution
{
public:
vector<int> singleNumber(vector<int>& nums)
{
size_t length = nums.size();
vector<int> results;
results.reserve(2);
if (0 == length) return results;
int axorb = 0;
for (size_t i = 0; i < length; i++)
axorb ^= nums[i];
int mask = axorb & (-axorb); // 取得axorb从低位向高位,第一个非0位所对应的数字
int a = 0;
int b = 0;
// axorb二进制位为1的位a和b一定不同,利用这个不为1的位将原数组元素分成两组异或即得结果
for (size_t i = 0; i < length; i++)
{
if (mask & nums[i]) a ^= nums[i];
else b ^= nums[i];
}
results.push_back(a);
results.push_back(b);
return results;
}
};
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?
分析:
两个相等的数异或结果为0。因此,首次扫描数组,得到两个单独的数a、b的异或结果axorb。因为a和b不相等,因此axorb一定不为0,且二进制位为1的位a和b一定不同。任取axorb中的一个不为0的二进制位,可以将原数组元素分成两组异或即得结果。
注:n & (-n)为n从低位向高位,第一个非0位所对应的数字
参考代码:
class Solution
{
public:
vector<int> singleNumber(vector<int>& nums)
{
size_t length = nums.size();
vector<int> results;
results.reserve(2);
if (0 == length) return results;
int axorb = 0;
for (size_t i = 0; i < length; i++)
axorb ^= nums[i];
int mask = axorb & (-axorb); // 取得axorb从低位向高位,第一个非0位所对应的数字
int a = 0;
int b = 0;
// axorb二进制位为1的位a和b一定不同,利用这个不为1的位将原数组元素分成两组异或即得结果
for (size_t i = 0; i < length; i++)
{
if (mask & nums[i]) a ^= nums[i];
else b ^= nums[i];
}
results.push_back(a);
results.push_back(b);
return results;
}
};
相关文章推荐
- Gradle之安装Gradle
- 嵌入式linux截图工具gsnap。。。。
- 翻译:深入 AngularUI Router
- 类与对象课后作业
- OC中NSLog函数输出格式详解
- 字符集
- 浅析mongodb主从库的配置
- POJ-2105
- json中头疼的null
- 豆瓣的前世今生
- 小学奥数 地球人口承载力估计
- 信息安全系统设计基础第六周学习总结
- latched之First Missing Positive
- 神奇的卷积神经网络(四)
- Android6.0网络权限管理
- java7 语法糖 之 switch 声明string
- linux如何执行后台进程
- Linux学习 -- Shell基础 -- Bash变量
- Linux核心设计依据(六)该块I/O一层
- setVisibility(View.GONE)无效的解决方案