题目描述
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
分析
参考:LeetCode 136 Single Number
参考:LeetCode 137 Single Number II
“相异为1”,所以一个数字异或本身为0,而0异或0仍为0, 一个数字异或0仍为这个数字。
0 ^ 0 = 0
n ^ 0 = n
n ^ n = 0
- 只有两个数a、b分别出现了一次,其余的数都是出现了两次
- 把整个数组异或,结果等于a^b,而a与b是不相等的,所以a^b必不为0
- 按照a^b结果其中一位,把数组分成两个,一组包含a,一组包含b,即问题变成LeetCode 136 Single Number
代码
public int[] singleNumber(int[] nums) {
int[] rt = new int[2];
int n = 0;
for (int v : nums) {
n ^= v;
}
int m = n & (~(n - 1));
for (int v : nums) {
if ((m & v) == 0) {
rt[0] ^= v;
} else {
rt[1] ^= v;
}
}
return rt;
}