【问题标题】:Finding all duplicates in an array [closed]查找数组中的所有重复项[关闭]
【发布时间】:2013-03-05 09:52:31
【问题描述】:

我正在学习 Java 编程的初学者课程。我正在尝试编写一个程序来查找并打印出数组中的重复项。这就是我到目前为止所拥有的。我被困住了。我想我需要if 之后的else 声明?

public class Array {
  public static void main(String[] args) {
    int N=10;        
    for (int i = 0; i < N - 1; i++)
    {
      for (int j = i + 1; j < N; j++)
      {
        if(i == j)
        {              
          System.out.println("Both arrays contain " + i);              
        }
      }
    }
  }
}

【问题讨论】:

  • 您还没有解释问题所在。你有什么问题?
  • 你的阵列在哪里?
  • 查看相关问题,我看到至少三个可以重复。

标签: java arrays loops nested duplicates


【解决方案1】:
public class Test15 {
  static int[] a = new int[]{1, 1, 1, 2, 3, 5, 3, 4, 5, 5};
  public static void main(String[] args){
    for (int i=0; i< a.length; i++) {
      boolean f = false;
      for (int j=i+1; j <a.length; j++)
        if (a[i]==a[j]) {
          System.out.println("duplicate ("+i+", "+j+")");
          f=true;
          break;
        }
      if (!f)
        System.out.println("unique ("+i+", "+a[i]+")");
    }
  }
}

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2019-05-29
    • 2022-08-14
    • 2022-01-23
    • 2018-03-30
    相关资源
    最近更新 更多