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:
[5, 3]
is also correct.class Solution { public: vector<int> singleNumber(vector<int>& nums) { int temp = 0 ; for(int i=0; i<nums.size(); ++i){ temp ^= nums[i]; } int mask = temp&(~(temp-1)); //找出第一个区别x,y的bit位,就是mask中的第一个1的位置。其他位置的操作让mask值0. int x = 0; int y = 0; for(int i=0; i<nums.size(); ++i){ if(nums[i]&mask){ //含有x和其他重复数字的子集 x ^= nums[i]; } else{ y ^= nums[i]; //含有y和其他重复数字的子集 } } return vector<int> {x,y}; } };