Solution by praneethgb


  • 0
    P

    Approach #1 Sort and verify neighbors [Accepted]

    Intuition

    Sort the given array elements and check every element with it's adjacent element
    to verify whether they are same or not. If yes add them to duplicates.

    Algorithm

    Suppose we have a function findDuplicates ....

    C++

    vector<int> findDuplicates(vector<int>& nums) {
           
           std :: sort(nums.begin(),nums.end());
           vector<int> Duplicates;
           int length = nums.size();
           for(int i=0;i<=length-1;i++)
           {
           
               if(nums[i]==nums[i+1]) 
               {
                   
                   Duplicates.push_back(nums[i]);
               }
               
           }
           
           return Duplicates;
       }
    

    Complexity Analysis

    • Time complexity : $$O(nlogn)$$.

    std::sort have average case (n log n) time complexity


Log in to reply
 

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