Algorithm: only numbers appear in the array once.

Source: Internet
Author: User

Algorithm: only numbers appear in the array once.
Question

In an integer array, all the numbers except two appear twice. Write a program to find the numbers that appear only once. The time complexity is O (n) and the space complexity is O (1 ).

Question

Tip1: if only one number appears in array A and the other number appears twice, it is very easy to find the number, the value is A [0] ^ A [1] ^... ^ A [n-1]
Therefore, you need to find a way to convert the problem to the problem scenario in tip1.
Tip2: returns the XOR of each number in the array in the question. The obtained value is x. In fact, x is the exclusive or value of the two numbers in the array that appear only once.
If the k of x is 1, all the numbers in the original array are divided into two arrays according to whether the k is 1.
Then we can implement the tip1 solution for the two arrays. Because each sub-array contains a number that only appears once, and the remaining number appears twice.

Code
#include 
  
   #include 
   
    #include 
    
     #include 
     
      #include 
      
       #include 
       
        using namespace std;class Solution {public: // A is an array, whose length is n void solve(int A[], int n) { int x = 0; for (int i = 0; i < n; i++) x ^= A[i]; // assert x != 0 int lowestBit = x - (x & (x-1)); int left = 0, right = n-1; while (left <= right) { while (left <= right && (A[left]&lowestBit) == 0) left++; while (left <= right && (A[right]&lowestBit) == 1) right--; if (left <= right) swap(A, left, right); } int x1 = 0, x2 = 0; for (int i = 0; i < left; i++) x1 ^= A[i]; for (int i = left; i < n; i++) x2 ^= A[i]; printf("x1:%d, x2:%d\n", x1, x2); } void swap(int A[], int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; }}; int main() { int A[] = {2, 3, 2, 4, 3, 5, 6, 7, 7, 6}; Solution solution; solution.solve(A, sizeof(A)/sizeof(int)); return 0;}
       
      
     
    
   
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.