Find two numbers that appear only once in the array, and find the number that appears once in the array.

Source: Internet
Author: User

Find two numbers that appear only once in the array, and find the number that appears once in the array.

Question: except two numbers in an integer array, the other numbers 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 ).

I still cannot understand it deeply.
The main idea of this question is the pattern of a number that appears only once in the previous array. An exclusive or operation is added for one traversal. Then the exclusive or value must be the difference or value of the two numbers that appear only once. The result of 1 in the binary representation of this value indicates that the two numbers are different on the bit. In this case, we can separate the two numbers that only appear once from the entire array using whether the bit is 1.

In this way, the numbers that appear twice will be grouped into the same group. The result is that there are two groups of data, each of which is an odd number and each has only one number.

# Include <stdio. h> # include <assert. h> int findOutTwo (int * a, int n, int & x, int & y) {assert (a); assert (n> 2 ); int result = a [0]; for (int I = 1; I <n; ++ I) result ^ = a [I]; int B = result &-result; x = 0; y = 0; for (int I = 0; I <n; ++ I) {if (B & a [I]) x ^ = a [I]; else y ^ = a [I];} return 0;} int main () {int a [] =, 4, 4, 5, 6}; int x, y; findOutTwo (a, sizeof (a)/sizeof (int), x, y); printf ("% d \ n ", x, y); getchar (); return 0 ;}

Result:

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.