Single number III

Source: Internet
Author: User

      • Title Description
      • Link Address
      • Solution
      • Algorithmic interpretation

Title Description

Given 2*n + 2 numbers, every numbers occurs twice except, find them.

Example

Given [1,2,2,3,4,4,5,3] return 1 and 5

Challenge

O (n) time, O (1) extra space.
.

Link Address

http://www.lintcode.com/en/problem/single-number-iii/

Solution
    vector<int>SINGLENUMBERIII ( vector<int>&a) {//Write your code here    intRET =0; for(inti =0; I < a.size ();    i++) {ret = ret ^ a[i]; }intLastoneval = ret-(Ret & (Ret-1)); vector<int>VEC1; vector<int>VEC2; for(inti =0; I < a.size (); i++) {if(A[i] & Lastoneval)        {Vec1.push_back (a[i]); }Else{Vec2.push_back (a[i]); }    }intRet1 =0;intRet2 =0; for(inti =0; I < vec1.size ();    i++) {Ret1 = Ret1 ^ vec1[i]; } for(intj =0; J < Vec2.size ();    J + +) {Ret2 = Ret2 ^ vec2[j]; } vector<int>Retvec;     Retvec.push_back (RET1); Retvec.push_back (Ret2);returnRetvec; }
Algorithmic interpretation

In front of the problem solved 2*n+1, is now facing the problem of 2*n+2, we want to use what method can be divided into two sets of 2*n+2 to 2*n+1, and then in each set by the XOR operation, and finally can get two values.
How to convert to 2*n+1, as long as the solution to this, then all the problems solved.
Solve the key: All the numbers are different or, get the final result, and then find the last nonzero position. According to this location, all of this position is zero for a group, and all of this position is one for a group.
Find the last one is 1 position, using the algorithm:
C-(C-1) &c get the last non-zero position composed of the number
If C = 1100, the result is 0100.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Single number III

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.