260. Single Number III
来源:互联网 发布:三年自然灾害真相知乎 编辑:程序博客网 时间:2024/04/24 15:40
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?
Solution 1 HashMap count the apperance of every number and pick out the number of appearance that does not equal 2
Solution 2 Bit manipulation
//https://leetcode.com/discuss/52351/accepted-java-space-easy-solution-with-detail-explanationspublic static int[] singleNumber(int[] nums) { // Pass 1 : // Get the XOR of the two numbers we need to find int diff = 0; for (int num : nums) { diff ^= num; } // Get its last set bit diff &= -diff; // Pass 2 : int[] rets = {0, 0}; // this array 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; }
0 0
- 260.Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- AT2 Homeomorphism and the group structure on a circle
- Linux/MIPS HOWTO
- [leetcode] 255. Verify Preorder Sequence in Binary Search Tree 解题报告
- codevs 1690 开关灯
- 比较两个树是否完全相同
- 260. Single Number III
- 引用未定义的控件
- eclipse启动不了,出现“Java was started but returned exit code=13......”对话框
- 文章标题
- 代码测试、调试与优化小结
- pthread与std::thread对比用法
- 如何理解wait前面需要加while循环
- 11.13 编程练习
- 有了CodinGame,玩着游戏就能学编程