Leetcode Problem 136:single Number

Source: Internet
Author: User

Description: Given An array of integers, every element appears twice except for one. Find the single one.

Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?

The topic requires O (n) time complexity, O (1) space complexity.

Idea 1: The initial use of brute force search, traversing the array, found that two elements are equal, then the two elements of the flag position is 1, and finally return the element with the flag bit 0. Time complexity O (n^2) no ac,status:time Limit exceed

1 classSolution {2  Public:3     intSinglenumber (intA[],intN) {4         5Vector <int> Flag (N,0);6         7          for(inti =0; I < n; i++)  {8             if(Flag[i] = =1)9                 Continue;Ten             Else    { One                  for(intj = i +1; J < N; J + +)  { A                     if(A[i] = =A[j]) { -Flag[i] =1;  -FLAG[J] =1; the                     } -                 } -             } -         } +          -          for(inti =0; I < n; i++)  { +             if(Flag[i] = =0) A                 returnA[i]; at         } -     } -};

Idea 2: Use XOR or operation. Nature of XOR 1: Commutative law a ^ b = b ^ A, nature 2:0 ^ a = A. Therefore, the Exchange law can be used to imagine the array of the same elements are all adjacent, so that all the elements in turn XOR or operation, the same element is different or 0, the final remaining element is a single number. Time complexity O (n), Spatial complexity O (1)

1 classSolution {2  Public:3     intSinglenumber (intA[],intN) {4         5         //XOR or6         intElem =0;7          for(inti =0; I < n; i++) {8Elem = elem ^A[i];9         }Ten          One         returnElem; A     } -};

Leetcode Problem 136:single 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.