jayati

Find duplicates in an array

Jan 6th, 2024
975
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution{
  7.   public:
  8.     vector<int> duplicates(long long arr[], int n) {
  9.         // code here
  10.         vector<int> ans;
  11.         sort(arr,arr+n);
  12.         for(int i=0;i<n-1;i++)
  13.         {
  14.             if(arr[i]==arr[i+1])
  15.             {
  16.                 if(ans.size()>=1)
  17.                 {
  18.                     if(ans[ans.size()-1]!=arr[i])
  19.                     {
  20.                          ans.push_back(arr[i]);
  21.                     }
  22.                    
  23.                 }
  24.                 else
  25.                 {
  26.                     ans.push_back(arr[i]);
  27.                 }
  28.                
  29.                
  30.             }
  31.         }
  32.         if(ans.size()==0)
  33.         {
  34.             return {-1};
  35.         }
  36.         return ans;
  37.     }
  38. };
  39.  
  40.  
  41. //{ Driver Code Starts.
  42. int main() {
  43.     int t;
  44.     cin >> t;
  45.     while (t-- > 0) {
  46.         int n;
  47.         cin >> n;
  48.         long long a[n];
  49.         for (int i = 0; i < n; i++) cin >> a[i];
  50.         Solution obj;
  51.         vector<int> ans = obj.duplicates(a, n);
  52.         for (int i : ans) cout << i << ' ';
  53.         cout << endl;
  54.     }
  55.     return 0;
  56. }
  57.  
  58. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment