面试题56 - I
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]
限制:
2 <= nums <= 10000
Solutions
bit operation
Use xor to remove numbers occurred two times and the resulting xored number
res
isnum1 ^ num2
.Then partition the whole array into two parts containing
num1
andnum2
in each part.Randomly choose one
1
bit inres
as the partition criteria.
Repeat the first step for each part.
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
int res = 0;
for (auto & n : nums)
res ^= n;
int lowbit = res & -res;
int num1 = 0, num2 = 0;
for (auto & n : nums) {
if (n & lowbit)
num1 ^= n;
else
num2 ^= n;
}
return {num1, num2};
}
};
Last updated
Was this helpful?