力扣,https://leetcode.cn/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/description/
题目:一个整型数组nums里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
注意:相同的数异或为0,不同的异或为1。0和任何数异或等于这个数本身。
思路:
Python
class Solution:
def sockCollocation(self, sockets: List[int]) -> List[int]:
x = 0
y = 0
n = 0
m = 1
for val in sockets:
n ^= val
while n & m == 0:
m <<= 1
for val in sockets:
if val & m == 0:
x ^= val
else:
y ^= val
return [x, y]
Java
class Solution {
public int[] sockCollocation(int[] sockets) {
int x = 0, y = 0, n = 0, m = 1;
for (int val : sockets) {
n ^= val;
}
while ((n & m) == 0) {
m <<= 1;
}
for (int val : sockets) {
if ((val & m) == 0) {
x ^= val;
} else {
y ^= val;
}
}
return new int[] {x, y};
}
}