In this Leetcode Single Number II problem solution, we have Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. You must implement a solution with a linear runtime complexity and use only constant extra space.

Leetcode Single Number II problem solution


Problem solution in Python.

def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return int((3*sum(set(nums))-sum(nums))/2)



Problem solution in Java.

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap();
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }
            else{
                map.put(nums[i],1);
            }
        }
        for(Integer values: map.keySet()){
            if(map.get(values)==1){
                return values;
            }
        }
        return -1;
    }
}


Problem solution in C++.

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int i=0;
        int j=0;
        for(int k:nums){
            i=~j&(i^k);
            j=~i&(j^k);
        }
      return i ;  
    }
};


Problem solution in C.

int partition(int *nums, int l, int r){
    int i = l,j = l;
    int t = l + rand()%(r-l+1);
    int tmp,p;
    p = nums[t];
    nums[t] = nums[r];
    nums[r] = p;
    
    for ( ; i <= r; i++){
        if (nums[i] <= p ){
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j++] = tmp;
        }
    }return j;
}

int singleNumber(int* nums, int numsSize) {
    int i = 0, j = numsSize-1;
    int par;
    while(i<j){
        par = partition(nums,i,j);
        if (par%3 == 0){
            i = par;
        } else j = par-1;
    }
    return nums[i];
}