Header Ad

Leetcode Single Number III problem solution

In this Leetcode Single Number III problem solution, we have given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

Leetcode Single Number III problem solution


Problem solution in Python.

def singleNumber(nums):
    a = set(nums)
    b = a.copy()
    for n in nums:
        if n in a:
            a.remove(n)
            continue
        if n in b: b.remove(n)
    return list(b)



Problem solution in Java.

class Solution {
    public int[] singleNumber(int[] nums) {
        int a = 0;
        int b = 0;
        int xor = 0;
        
        //get all xor
        for(int n : nums) xor = xor ^ n;
        
        //discover any set bit on the result, I'm using the first one
        int firstSetBit = 0;
        while(firstSetBit < 32) if ( ((xor>>firstSetBit)&1) == 1 ) break; else firstSetBit++;
        
        //put numbers with the corresponding bit set to zero into one variable
        //and if it is set to one, put it into the other variable
        for(int n : nums) {
            if ( ((n>>firstSetBit)&1) == 0 ) a ^= n;
            else b ^= n;
        }
        
        return new int[]{a,b};
    }
}


Problem solution in C++.

public:
    vector singleNumber(vector& nums) {
        vector op;
        long long int xorpair=0;
        for(auto &i:nums)
        {
            xorpair^=i;
        }
        long long int rsbm=xorpair&(-xorpair);
        long long int on=0;
        long long int off=0;
        for(auto &i:nums)
        {
            if(i&rsbm)
                on^=i;
            else
                off^=i;
        }
        op.push_back((int)(on^xorpair));
        op.push_back((int)(off^xorpair));
        return op;
        
    }
};


Problem solution in C.

int* singleNumber(int* nums, int numsSize, int* returnSize) {
    int i, *ret = calloc(*returnSize = 2, sizeof(int));
    for(i = 0; i < numsSize; ret[0] ^= nums[i++]);
    for(i = 0; i < numsSize; i++)
        if(nums[i] & ret[0] & -ret[0])
            ret[1] ^= nums[i];
    ret[0] ^= ret[1];
    return ret;
}


Post a Comment

0 Comments