Leetcode: Single Number III
2015-12-23 05:43
381 查看
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?
Lintcode 也有这道题 Single Number III
example:
1 0 1 0 0 0
1 0 1 0 0 0
0 0 1 0 0 0
0 0 1 0 0 0
1 0 0 1 0 0
1 0 0 1 0 0
0 0 1 0 0 0
0 0 1 0 0 1
如例所示,最后两个数8,9即是所求Single Number, 即使它们能使某一位上的1凑成偶数(使得Single Number I 的方法不再有效)如上例从右到左第4位,但是始终会至少有某一位的1仍是奇数(如上例从右到左第一位)。
想法就是把这些数分成两拨,让这两个single number各在一拨,然后各自按Single Number I 的做法做,就可以找出来
取上述为1的各位中某一位,方便起见取最右边为1的那位,所有那位为1的数形成一拨,其余数形成另一拨,这样就把两个数分开到两拨了。各自XOR就可以得到两个数。
取最右边为1的那位的方法是:n & (~(n-1))
Single Number I的一个简便方法是XOR各个数,如果某一位的1的个数是奇数,XOR之后仍将为1.
public class Solution { public int[] singleNumber(int[] nums) { int[] res = new int[2]; int n = 0; for (int elem : nums) { n ^= elem; } n = n & (~(n-1)); for (int elem : nums) { if ((n & elem) == n) { res[0] ^= elem; } else res[1] ^= elem; } return res; } }
相关文章推荐
- 一个可以限制执行时间的命令timeout
- CentOS 7 ARM 版正式发布:支持树莓派2/香蕉派/CubieTruck
- 普法知识(47):违反政治纪律案件分析(续)
- LeetCode - Valid Sudoku
- 316. Remove Duplicate Letters
- 理解并取证:以太通道的动态协商机制的工作原理
- 理解并取证:以太通道的动态协商机制的工作原理 推荐
- LeetCode - Search Insert Position
- Leetcode: 3Sum Smaller
- 手机号归属地查询接口
- LeetCode - Search for a Range
- 华为USG统一安全边界网关的设计、演示、经验鉴证实评-卷A
- centos6.5 安装vlc播放器
- ajaxfrom
- Dubbo的正确打开方式之基本接口定义及异常处理
- Chrome 插件,Andriod 手机和电脑同步显示。
- [转] android 中 任务、进程和线程的区别
- 多线程的卖票示例和同步
- Android笔记(六十四) android中的动画——补间动画(tweened animation)
- LazyLaod.js用法