ACWING73. Array appears only once in the two numbers (to prove safety offer)

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:

  1. XOR is a number of 0 twice
  2. All XOR again obtained sum = x ^ y
  3. Take k, k-th bit to ensure that a sum
  4. Again vector traversal, if a k-th bit of the number of XOR. After the operation, the structure is the first answer
  5. 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};
    }
};
Published 843 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/104996973