Topic:
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?
Analysis:
Two equal number XOR or result is 0. Therefore, for the first time, the array is scanned, resulting in two separate numbers a, B, or result axorb. Because A and B are unequal, Axorb must not be 0, and bits A and B bits 1 must be different. In any axorb, you can divide the elements of the original array into two sets of XOR results, which are not 0 bits.
Note: N & (-N) is n from low to high, the number corresponding to the first non-0 digit
Reference code:
Class Solution{public: vector<int> singlenumber (vector<int>& nums) { size_t length = Nums.size (); vector<int> results; Results.reserve (2); if (0 = = length) return results; int axorb = 0; for (size_t i = 0; i < length; i++) Axorb ^= nums[i]; int mask = Axorb & (-axorb); Get Axorb from low to high, the first non-0 digits corresponding to the number int a = 0; int b = 0; Axorb bits is 1 bits A and B must be different, using this non-1 bit to divide the original array elements into two sets of XOR results for (size_t i = 0; i < length; i++) { if (Mask & N Ums[i]) a ^= nums[i]; else b ^= nums[i]; } Results.push_back (a); Results.push_back (b); return results;} ;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode:single number III