In addition to an array of integers in two numbers, the other numbers appear twice.
Please write a program to find these two figures appear only.
You can assume that there must be two numbers.
Sample
input: [1,2,3,3,4,4]
Output: [1,2]
Ideas:
Simple idea is to spend the extra space.
Solution to a problem is the use of exclusive OR operation:
- XOR is a number of 0 twice
- All XOR again obtained sum = x ^ y
- Take k, k-th bit to ensure that a sum
- Again vector traversal, if a k-th bit of the number of XOR. After the operation, the structure is the first answer
- The second answer is the sum XOR's first answer.
class Solution {
public:
vector<int> findNumsAppearOnce(vector<int>& nums) {
int sum = 0;
for(auto x: nums) {
sum ^= x;
}
int k = 0;
while(!((sum >> k) & 1)) k++;
int ans = 0;
for(auto x: nums) {
if((x >> k) & 1) ans ^= x;
}
return vector<int>{ans,sum ^ ans};
}
};