Solving notes (24) -- find two numbers that appear only once in the array (array)

Source: Internet
Author: User

Problem description: 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 ).

Idea: if only one number appears only once, and the other two appear, you can directly perform an exclusive or operation on all numbers, because equal numbers are different or the result is 0. If two numbers appear only once, the other numbers appear twice. What should I do? The book "The beauty of programming" provides a method to first perform an exclusive or operation on all numbers to obtain a number, and then use a non-zero bit of the number as the filter bit, divide the array into two parts. The number that appears only once is divided into different parts. Now the problem occurs only once. You can perform an exclusive or operation on each part.

Reference code:

// Function: find two numbers that only appear once in the array // function parameter: arr is the source array, Len is the number of array elements, and result is used to store the result // return value: no void findisolatetwo (int * arr, int Len, int * result) {int I, all = 0, flag = 1; for (I = 0; I <Len; I ++) // All numbers are different or all ^ = arr [I]; while (! (ALL & flag) // search for the filter Bit Flag <= 1; Result [0] = Result [1] = 0; for (I = 0; I <Len; I ++) // use a filter bit to distinguish {If (flag & arr [I]) result [0] ^ = arr [I]; elseresult [1] ^ = arr [I] ;}}

I enjoy the copyright of blog articles, reprint please indicate the source

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: 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.