C code to use ZERO memory, with linear time


  • 0
    D

    No any tmp var, including (int i) in for-loop, thus ZERO memory.
    XOR operation over each elements once to get same elements disappear, leaving the unique one, thus linear time.

    int singleNumber(int* nums, int numsSize) {
        if(numsSize == 1){
            return nums[0];
        }
        else{ // numsSize is an odd num larger than 1
            nums[0] ^= nums[1]; // to get nums[1] a tmp var
            for(nums[1]=2; nums[1]<numsSize; nums[1]++){
                nums[0] ^= nums[nums[1]];
            }
            return nums[0];
        }
    }
    

Log in to reply
 

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