[Leetcode OJ] Single number one of the--given an array of integers, every element appears twice except in. Find the single one.

Source: Internet
Author: User

1 classSolution {2  Public:3     intSinglenumber (intA[],intN) {4         inti,j;5          for(i=0; i<n; i++)6         {7              for(j=i+1; j<n; J + +)8             {9                 if(a[j]==A[i])Ten                 { One                     inttemp = a[i+1]; Aa[i+1] =A[j]; -A[J] =temp; -i++; the                      Break; -                 } -             } -             if(j==N) +                 returnA[i];  -         } +     } A};

The above is the traditional method, the time complexity is O (N2), the space complexity is O (1).

1 classSolution {2  Public:3     intSinglenumber (intA[],intN) {4         intresult=0;5          for(intI=0; i<n; i++)6result = result ^A[i];7         returnresult;8     }9};

The time complexity and space complexity are all O (1) by using bitwise XOR OR operation.

The nature of the commutative law and the binding law is used for the XOR operation.

Exchange Law: a^b = B^a

Binding law: (a^b) ^c = a^ (b^c)

In addition, a^a=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.