197.md 1.7 KB
Newer Older
W
wizardforcel 已提交
1
# Java 难题 – 查找所有重复的元素
W
wizardforcel 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

> 原文: [https://howtodoinjava.com/puzzles/find-all-duplicate-elements/](https://howtodoinjava.com/puzzles/find-all-duplicate-elements/)

**难题:**给定 n 个正整数的输入数组,其中整数是随机顺序的。 该数组中的每个数字可以出现多次。 您需要找到所有不同的元素并将所有这些元素放在一个数组中,即 output1。 如果输入中没有重复的数字,则输出应为{-1}。

**输入规格:输入:输入 2 中的元素数(n)输入 2:n 个正整数数组**

输出规格:输出:在 input2 中重复的不同元素的数组

```java
Example 1: input : 6 input2 : {4,4,7,8,8,9} output : {4,8} 
Example 2: input : {2,3,6,8,90,58,58,60} output : {58} 
Example 3: input : {3,6,5,7,8,19,32} output : {-1}
```

W
wizardforcel 已提交
17
## 解决方案
W
wizardforcel 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

```java
import java.util.HashSet;
import java.util.Set;

public class DuplicatesInArray
{
    public static void main(String[] args)
    {
        Integer[] array = {1,2,3,4,5,6,7,8};  //input 1
        int size = array.length;              //input 2

        Set<Integer> set = new HashSet<Integer>();
        Set<Integer> duplicates = new HashSet<Integer>();

        for(int i = 0; i < size ; i++)
        {
            if(set.add(array[i]) == false)
            {
                duplicates.add(array[i]);
            }
        }

        if(duplicates.size() == 0)
        {
            duplicates.add(-1);
        }

        System.out.println(duplicates);
    }
}
```

上面的程序将从数组中找到所有重复的元素,并将它们放入单独的集合中。 您可以在此处找到有关此逻辑的更多讨论://howtodoinjava.com/java/interviews-questions/find-duplicate-elements-in-an-array/

学习愉快!