260. Single number III
- Total accepted:42076
- Total submissions:91382
- Difficulty:medium
Given An array of numbers nums
, in which exactly-elements appear only once and all the other elements appear exactly Twice. Find the 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. The above example, is
[5, 3]
also correct.
- Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity?
Ideas:
A^a=0.
Only 2 numbers in the nums are unique and set to a, B, then the A^B is obtained after the nums all the elements are different or manipulated. A and B are not equal on some bits, so c=a^b!=0 (c is a binary number). So first find A and B unequal (can be from right to left the first 1 bit), that is c[i]==1, and then according to C[i] nums elements into 2 categories: to C[i] contributed 1 and to C[i] contributed 0,a and B are divided into different classes, and then in the respective class XOR or operations get a and B.
Note Operator Precedence: non-and take-back operation > Subtraction Operation >== operation > with OR, XOR, same or operation
Code:
1 classSolution {2 Public:3vector<int> Singlenumber (vector<int>&nums) {4 intXor=0;5 for(intI=0; I<nums.size (); i++) xor^=Nums[i];6xor&=-xor;//take a bit from right to left, first 17vector<int> Res (2,0);8 for(intI=0; I<nums.size (); i++){9 //The following if-else can also be written as res[! ( Xor&diff)]^=nums[i];Ten if((xor&nums[i]) = =0){ Oneres[0]^=Nums[i]; A } - Else{ -res[1]^=Nums[i]; the } - } - returnRes; - } +};
Leetcode 260. Single number III