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:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
思路:两个相同数异或为0,结果中任一为1位,数分组;
注意:&按位与操作优先级低于==
参考:http://blog.csdn.net/sbitswc/article/details/48410781
1 class Solution { 2 public: 3 vector<int> singleNumber(vector<int>& nums) { 4 int tmp = 0; 5 int len = nums.size(); 6 for(int i=0;i<len;i++) 7 { 8 tmp ^= nums[i]; 9 } 10 tmp &= (-tmp); 11 vector<int> ans(2,0); 12 for(int i=0;i<len;i++) 13 { 14 if((tmp&nums[i])==0) 15 ans[0] ^= nums[i]; 16 else 17 ans[1] ^= nums[i]; 18 19 } 20 return ans; 21 } 22 };