合并2数组并删除重复输入

drkbr07n  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(343)

我有一个问题,如何删除重复值的数组,有人能帮我吗?我有这个代码只是为了合并2个数组和显示结果,但我不知道如何删除重复的输入(对不起,我刚开始学java。)

  1. public static void main(String... args) {
  2. int[] x = new int[3];
  3. int[] y = new int[3];
  4. int[] xy = new int[6];/***new array to hold the integers of arrays x and y****/
  5. int temp, c = 0;
  6. Scanner myInput = new Scanner(System.in);
  7. /***input of array x at the same time storing the integers to array xy***/
  8. System.out.println("enter 3 integers for array x:");
  9. for (int a = 0; a < 3; a++) {
  10. x[a] = myInput.nextInt();
  11. xy[c] = x[a];
  12. c++;
  13. }
  14. /***input of array y at the same time storing the integers to array xy***/
  15. System.out.println("enter 3 integers for array y:");
  16. for (int b = 0; b < 3; b++) {
  17. y[b] = myInput.nextInt();
  18. xy[c] = y[b];
  19. c++;
  20. }
  21. /*sorting...*/
  22. for (int i = 0; i < 6; i++) {
  23. for (int j = 0; j < 5 - i; j++) {
  24. if (xy[j] > xy[j + 1]) {
  25. temp = xy[j];
  26. xy[j] = xy[j + 1];
  27. xy[j + 1] = temp;
  28. }
  29. }
  30. }
  31. /*printing of array xy sorted*/
  32. for (int w = 0; w < 6; w++)
  33. System.out.print(xy[w] + " ");
  34. }
xienkqul

xienkqul1#

由于已对合并数组进行排序,因此简化的解决方案是在打印时不删除重复项,而是通过比较循环中的当前值和前一个值来过滤掉它们

  1. System.out.print(xy[0] + " ");
  2. for (int w = 1; w < 6; w++) {
  3. if (xy[w] != xy[w - 1]) {
  4. System.out.print(xy[w] + " ");
  5. }
  6. }

相关问题