001. 只出现一次的数字 III
解法一:哈希表
class Solution {
public int[] singleNumber(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
Integer count = map.getOrDefault(nums[i], 0);
count++;
if (count >= 2) {
map.remove(nums[i]);
} else {
map.put(nums[i], count);
}
}
Set<Integer> keys = map.keySet();
int index = 0;
for (Integer key : keys) {
result[index] = key;
index++;
}
return result;
}
}
空间复杂度 O(n),不满足要求
解法二:位运算
关键点:
- 如果 a == b,则 a ^ b == 0
- 异或运算满足交换律,所以如果将数组中的所有数异或的话,最后的结果等于我们所要寻找的两个数的异或
- 但是仅仅知道 target1 ^ target2 == xory 的条件是不够的
- x & (-x) 可以将 x 的各个位都变成 0,除了最低位的 1
- 通过这种方式,将 xory 变成 0000…00100…0 的形式,设不为零的那位是第 n 位
- 那么,可以断定 target1 和 target2 的第 n 位是不一样的
- 我们就根据第 n 位是否位 1 将数组中的数分成两组,对这两组分别全都求异或,那两组中最后的结果就是两个目标值
class Solution {
public int[] singleNumber(int[] nums) {
int len = nums.length;
int xory = 0;
for (int i = 0; i < len; i++) {
xory ^= nums[i];
}
xory = xory == Integer.MIN_VALUE ? xory : xory & (-xory);
int type1 = 0;
int type2 = 0;
for (int num : nums) {
if ((num & xory) != 0) {
type1 ^= num;
} else {
type2 ^= num;
}
}
return new int[]{type1, type2};
}
}
空间复杂度 O(1),满足要求