原文: https://howtodoinjava.com/puzzles/find-all-duplicate-elements/

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

输入规格

输入 1:输入 2 中的元素数(n)

输入 2:n 个正整数的数组

输出规格:

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

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

解决方案

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. public class DuplicatesInArray
  4. {
  5. public static void main(String[] args)
  6. {
  7. Integer[] array = {1,2,3,4,5,6,7,8}; //input 1
  8. int size = array.length; //input 2
  9. Set<Integer> set = new HashSet<Integer>();
  10. Set<Integer> duplicates = new HashSet<Integer>();
  11. for(int i = 0; i < size ; i++)
  12. {
  13. if(set.add(array[i]) == false)
  14. {
  15. duplicates.add(array[i]);
  16. }
  17. }
  18. if(duplicates.size() == 0)
  19. {
  20. duplicates.add(-1);
  21. }
  22. System.out.println(duplicates);
  23. }
  24. }

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

学习愉快!