Java accepted solution with comments (4-11ms run time)


  • 3
    S
    public int singleNumber(int[] nums) {
        // create a counter for each bit position
        int[] bits = new int[32];
        // loop through all bits for all nums
        // if current bit is not 0, add 1 to counter
        int mask = 1;
        for (int j=0; j<32; j++) {
            for (int i=0; i<nums.length; i++) {
                bits[j] += (mask & nums[i]) != 0 ? 1: 0;
            }
            mask = mask << 1;
        }
        // only loop through all bits
        // if bit counter is not multiple of 3
        // add set the bit in result to 1
        int result = 0;
        mask = 1;
        for (int i=0; i<32; i++) {
            if (bits[i] % 3 != 0) {
                result = (result | mask);
            }
            mask = mask << 1;
        }
        // return result
        return result;
    }
    

    I found this very interesting: if I delete all the comments, it finishes in 4ms, while I keep the comments, it finishes in 11ms.


  • 0
    K

    wow! mind = blown! awesome solution


  • 0
    H

    does O(1) space meet the requirement of "no extra space"?


  • 0
    S

    I think so, or the question will probably say in place.


  • 0
    C

    why not just use "mask & nums[i]" instead of "(mask & nums[i]) != 0 ? 1: 0;"


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.