【问题标题】:I want to find unique duplicates value in array,but i am not getting below is my code in java我想在数组中找到唯一的重复值,但我没有得到下面是我在 java 中的代码
【发布时间】:2021-12-15 18:37:54
【问题描述】:
`
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);
}
}`

我的示例输入是:1 2 2 2 3 我得到像这样的输出 2 重复 2 重复 2 重复

我需要唯一的重复输出怎么做。

【问题讨论】:

  • 尝试使用Set
  • 是不是不能通过修改这段代码得到
  • 可以,但是效率很低。
  • 那么你能在上面的代码中建议如何做到这一点...
  • 我能想到的唯一方法是创建一个额外的数组,对于您找到的每个重复项,如果该数组尚未包含它(没有重复项),请将其添加到该数组中。跨度>

标签: java arrays sorting


【解决方案1】:

尝试使用列表,

然后检查列表是否包含重复项

如果没有 如果存在,则将副本添加到列表中

打印重复列表

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:
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);
    }
}

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多