[Xiaomi] shaped number

Source: Internet
Author: User

In a shaped array of length n, the other numbers appear 2 times except that three digits appear only once. Please write the program output any one occurrence of the number, the program time and space complexity of the smaller the better. For example: a = {1,3,7,9,5,9,4,3,6,1,7}, output 4 or 5 or 6.

Thinking of solving problems
    • If only one occurrence occurs only once, all the numbers are made in an XOR or operation, returning their values.
    • If there are two numbers appearing only once, assuming A and B, the result of all the XOR operations is x=a^b, because A and B are unequal, so X is not 0. Scan from right to left for the first 1 bit, according to whether it is 1, divide the original array into two groups, and then treat each group of data according to the situation.
    • For cases where three numbers occur only once, they can be solved according to three number 22 XOR, the lowest bit having two identical, and one difference .
Implementation code
#include <iostream>using namespace STD;intLowbit (intx);intFindint*num,intLen);intMain () {intNum[] = {1,1,2,2,3,3,4,4,5,6,7};cout<<find (NUM,sizeof(num)/sizeof(num[0])) <<endl;return 0;}//Find out where the first 1 appears from right to leftintLowbit (intx) {returnX & ~ (X-1);}intFindint*num,intLen) {intXORs =0; for(inti =0; i < Len;    i++) {xors ^= num[i]; }//Three number 22 XOR, the lowest bit has two identical, there is a different    intLow =0; for(inti =0; i < Len; i++) {//indicates low = Lowbit (a^b) ^ lowbit (a^c) ^ lowbit (b^c)Low ^= lowbit (xors ^ num[i]); }intresult =0; for(inti =0; i < Len; i++) {if(Lowbit (xors ^ num[i]) = = low)        {result ^= num[i]; }    }returnResult;}

[Xiaomi] shaped number

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.