Header Ad

Leetcode Find All Duplicates in an Array problem solution

In this Leetcode Find All Duplicates in an Array problem solution we have given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

Leetcode Find All Duplicates in an Array problem solution


Problem solution in Python.

class Solution(object):
    def findDuplicates(self, nums):
        result = []
        for x in nums:
            if nums[abs(x)-1] < 0:
                result.append(abs(x))
            else:
                nums[abs(x)-1] = -1*nums[abs(x)-1]
        return result



Problem solution in Java.

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> ans=new ArrayList<Integer>();
        for(int i=0;i<nums.length;i++){
            if(nums[Math.abs(nums[i])-1]<0) ans.add(Math.abs(nums[i]));
            else nums[Math.abs(nums[i])-1]=-nums[Math.abs(nums[i])-1];
        }
        return ans;
    }
}


Problem solution in C++.

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int n=nums.size(), i=0;
        vector<int> ans;
        for(int i=0; i<n; i++){
            if(nums[abs(nums[i])-1]<0){
                ans.push_back(abs(nums[i]));
            }
            nums[abs(nums[i])-1]*=-1;
        }
        return ans;
    }
};


Problem solution in C.

int* findDuplicates(int* nums, int numsSize, int* returnSize)

{   int arr[numsSize];

    for(int i = 0; i<numsSize; i++)  arr[i] = i+1;
 
    int c[numsSize];
    
   for(int i = 0; i<numsSize;i++)  c[i] = 0;
 
   int i = 0; 
   while(i<numsSize)
    {
         if (nums[i]==arr[nums[i]-1]) c[nums[i]-1]++ ;
         i++;
     }
 
 
int*a = (int*) malloc(numsSize*sizeof(int));
  
  int j = 0;
  for(int i = 0; i<numsSize; i++)
    {
        if(c[i]==2)    { a[j] =i+1;  j++; }        
    }
    
    a =  (int*) realloc(a,j*sizeof(int));
    *returnSize = j;
    return a;    
}


Post a Comment

0 Comments