Single Number III & 数组中只出现一次的数字
2015-12-05 16:20
375 查看
Given an array of numbers
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
Note:
The order of the result is not important. So in the above example,
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.
Subscribe to see which companies asked this question
Hide Tags
Bit Manipulation
Show Similar Problems
进行两遍异或。
第一遍异或所有元素,得到我们要找的两个元素的异或值。因为我们要找的两个数是不一样的,所以他们异或的结果中肯定有位被置为1.找到其中任意一个被置为1的位,这里我们找最后一个被置为1的位。
第二遍,根据最后一位是否为1,将所有的数分成两组,那么我们要找的两个数必定属于不同的组。然后对这两组分别异或所有元素,就可以得到要找的数了。
注意位操作。
通过将一个数与它的负绝对值进行按位与,可以得到最低位的1。
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.
Subscribe to see which companies asked this question
Hide Tags
Bit Manipulation
Show Similar Problems
进行两遍异或。
第一遍异或所有元素,得到我们要找的两个元素的异或值。因为我们要找的两个数是不一样的,所以他们异或的结果中肯定有位被置为1.找到其中任意一个被置为1的位,这里我们找最后一个被置为1的位。
第二遍,根据最后一位是否为1,将所有的数分成两组,那么我们要找的两个数必定属于不同的组。然后对这两组分别异或所有元素,就可以得到要找的数了。
注意位操作。
通过将一个数与它的负绝对值进行按位与,可以得到最低位的1。
class Solution { public: vector<int> singleNumber(vector<int>& nums) { // Pass 1 : // Get the XOR of the two numbers we need to find int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>()); // Get its last set bit diff &= -diff; // Pass 2 : vector<int> rets = {0, 0}; // this vector stores the two numbers we will return for (int num : nums) { if ((num & diff) == 0) // the bit is not set { rets[0] ^= num; } else // the bit is set { rets[1] ^= num; } } return rets; } };
相关文章推荐
- 黑马程序员--java基础之类与对象
- AES算法 Java实现
- 基于webmagic的爬虫项目经验小结
- 12月5日笔记
- 一亿以内素数超优算法
- 下载附件文件名乱码问题
- LIBSVM使用介绍
- 图像预处理与特征提取(1)——白化处理和直方图均衡化
- Linux驱动程序中的platform总线详解
- POJ 1337
- 杭电ACM2501——Tiling_easy version
- 第二章 使用SQLite数据库
- 热带水果的收藏(三亚)
- iOS开发——监听耳机状态(是否插入)
- matlab之reshape函数
- P53 T2
- HDOJ--2674--N!Again
- Linux系统分区建议
- linux xargs命令的使用及其与exec、管道的区别
- python编码检测模块chardet