LeetCode – Single Number II (Java)

Problem

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

Java Solution

This problem is similar to Single Number.

public int singleNumber(int[] A) {
    int ones = 0, twos = 0, threes = 0;
    for (int i = 0; i < A.length; i++) {
        twos |= ones & A[i];
        ones ^= A[i];
        threes = ones & twos;
        ones &= ~threes;
        twos &= ~threes;
    }
    return ones;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • alexwest11

    see above

  • alexwest11

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

    not clear. ‘single one’ can be 1 ,2 or any number over3???

    lets say all 3times, and single 1time
    #1 xor elements. it will each one once 111 222 333 4 -> 1 2 3 4

    #2 sum all elements:
    #3 deduct from 2step sum of step1, 3 times,thus on exit it is -8
    ——–
    lets say all 3times, single one is twice.
    same only on step #1 it is all w/out 4
    so, after same stesp, it is 8 in the end,.

    NOT SURE IF NUMBER occur any number >3 ???

  • alexwest11

    so we have 333 111 222 44,

    #1 xor all those give up : ‘3 1 2 ‘ xor twice make it 0.

    #2 sum all those 33 111 222 44
    #3 deduct 3times 3 2 1 from step2
    we have only 44. divide 2 vuala!!

    done in loop..i guess.

    is is as solution???????

  • Milos Kosanovic


    public int singleNumber(int[] A){
    List list=Arrays.stream(A).boxed().collect(Collectors.toList());
    int number=0;
    for(int i=0;i<A.length;i++){
    if(Collections.frequency(list, A[i])==1){
    number=A[i];
    }
    }
    return number;
    }

  • nagen
  • dwaijam
  • Shailesh Agarwal

    can you provide the explanation. Looks complicated.