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.
Example:
Input: [1,2,1,3,2,5]
Output: [3,5]
Note:
[5, 3] is also correct.给定一个数组,其中只有两个数只出现了一次,其他所有数都出现了两次。要求找出这两个数。
最简单的做法就是使用Set进行操作,将已出现过的从Set中除去,将未出现过的加入到Set中。最后留下的就是要找的两个数。
与 0136. Single Number 使用的方法相同,用异或找出这两个数a和b,具体方法如下:
class Solution {
public int[] singleNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (set.contains(num)) {
set.remove(num);
} else {
set.add(num);
}
}
int[] ans = new int[set.size()];
int index = 0;
for (int num : set) {
ans[index++] = num;
}
return ans;
}
}
class Solution {
public int[] singleNumber(int[] nums) {
int[] ans = new int[2];
int xor = 0;
for (int num : nums) {
xor ^= num;
}
int pos = 1;
while ((xor & pos) == 0) {
pos <<= 1;
}
for (int num : nums) {
if ((num & pos) == 0) {
ans[0] ^= num;
} else {
ans[1] ^= num;
}
}
return ans;
}
}
/**
* @param {number[]} nums
* @return {number[]}
*/
var singleNumber = function (nums) {
let xor = 0
for (let num of nums) {
xor ^= num
}
let pos = 1
while (!(pos & xor)) {
pos <<= 1
}
let a = 0
let b = 0
for (let num of nums) {
if (num & pos) {
a ^= num
} else {
b ^= num
}
}
return [a, b]
}
参考
LeetCode 260. Single Number III 题解
原文:https://www.cnblogs.com/mapoos/p/13369924.html