Home > front end >  I want to find unique duplicates value in array,but i am not getting below is my code in java
I want to find unique duplicates value in array,but i am not getting below is my code in java

Time:11-01

`
import java.util.Scanner;
public class duplicateValue {
    public static void reverse(int[] a)
    {
        for(int i=0;i<a.length;i  )
        {
            {
         for(int j=i 1;j<a.length;j  )
             if((a[i]==a[j]))
             {
                 System.out.println(a[i] " is duplicated");

             }
            }
             
        }
    }
public static void main(String[] args)
{
    Scanner sc=new Scanner(System.in);
    System.out.println("enter the size of array");
    int n=sc.nextInt();
    System.out.println("enter the " n "no. of elements");
    int[] a=new int[n];
    for(int i=0;i<n;i  )
    {
        a[i]=sc.nextInt();
    }
    reverse(a);
}
}`

My sample input is : 1 2 2 2 3 I am getting output like 2 is duplicated 2 is duplicated 2 is duplicated

I need unique duplicate outupt how to do it.

CodePudding user response:

Try using a list,

then check if the list contains the duplicate

if not add a duplicate to the list if present

print list of duplicates

CodePudding user response:

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class duplicateValue {
    public static void reverse(int[] a)
    {
        HashMap<Integer, Integer> map = new HashMap<>();
        
        for (int element : a) 
        {   
            if(map.get(element) == null)
            {
                map.put(element, 1);
            }
            else
            {
                map.put(element, map.get(element) 1);
            }
        }
        Set<Entry<Integer, Integer>> entrySet = map.entrySet();
            
        for (Entry<Integer, Integer> entry : entrySet) 
        {               
            if(entry.getValue() > 1)
            {
                System.out.println("Duplicate Element : " entry.getKey() " - found " entry.getValue() " times.");
            }
        }
    }

    public static void main(String[] args)
    {   
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the size of array");
        int n = sc.nextInt();
        System.out.println("enter the " n "no. of elements");
        int[] a = new int[n];
        for(int i=0;i<n;i  )
        {
            a[i] = sc.nextInt();
        }
        reverse(a);
    }
}
  • Related