LeetCode-137 Single number II

Source: Internet
Author: User

Given an array of integers, every element appears three times except for one. Find the single one.

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

Ideas:

Consider all binary representations, if we take the sum of all the numbers on the first th position and the 3, then there will only be two results 0 or 1 (according to test instructions, 3 0 or 3 1 Add the remainder to 0). So the result of the remainder is that "single number".

A straightforward implementation is to use an array of size 32 to record the and on all bits.

intSinglenumber (intA[],intN) {intCOUNT[32] = {0}; intresult = 0;  for(inti = 0; I < 32; i++) {     for(intj = 0; J < N; J + +) {      if((A[j] >> i) & 1) {Count[i]++; }} result|= ((Count[i]% 3) <<i); }  returnresult;}

Improved:

This algorithm has improved space and can be used with mask variables:

    1. onesMask variable that represents only one occurrence of the first th bit
    2. twosMask variable representing only two occurrences of the first th bit

Assuming that there are 3 consecutive 5 occurrences at the beginning of the array, the change is as follows:

ones = 101twos = 0--------------ones = 0twos = 101--------------ones = 0twos = 0--------------  
When the first th bit appears 3 times, we set the ones first twos th bit to 0. The final answer is ones.

The code is as follows:
 Public intSinglenumber (int[] A) {intone = 0; intboth = 0; inttmp;  for(inti=0; i<a.length; i++) {= (A[i] & one) |both ; One= one ^A[i]; TMP= ~ (One &); One= one &tmp; both= &tmp; }        returnOne ; }

The above analysis section references the self-propelled cool: http://www.tuicool.com/articles/fAZZv2a

LeetCode-137 Single number II

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.