260. Single Number III
- Total Accepted: 42076
- Total Submissions: 91382
- Difficulty: Medium
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?
思路:
a^a=0。
nums中只有2个数是唯一,设为a,b,那么对nums所有元素异或操作以后得到的是a^b。a和b在某些位上是不相等的,所以c=a^b!=0(c是二进制数)。所以先找到a和b不相等的某一位(可以是由右向左第一个为1的位),也就是c[i]==1;再根据c[i]将nums中的元素分为2类:对c[i]贡献了1和对c[i]贡献了0,a和b被分到不同类中,再在各自类中异或操作得到a和b。
这里注意操作符优先级:非和取反操作>加减乘除操作>==操作>与或、异或、同或操作
代码:
1 class Solution { 2 public: 3 vector<int> singleNumber(vector<int>& nums) { 4 int Xor=0; 5 for(int i=0;i<nums.size();i++) Xor^=nums[i]; 6 Xor&=-Xor;//取由右向左第一个为1的位 7 vector<int> res(2,0); 8 for(int i=0;i<nums.size();i++){ 9 //下面的if-else也可以写成res[!(Xor&diff)]^=nums[i]; 10 if((Xor&nums[i])==0){ 11 res[0]^=nums[i]; 12 } 13 else{ 14 res[1]^=nums[i]; 15 } 16 } 17 return res; 18 } 19 };