【问题标题】:How to find duplicates in a java array using only for, if or while?如何仅使用 for、if 或 while 在 java 数组中查找重复项?
【发布时间】:2015-01-27 22:04:25
【问题描述】:

谁能解释我如何在 java: array {1,5,7,4,5,1,8,4,1} 中查找重复元素,仅使用 for、if 或 while/do while?

提前发送。

别墅

【问题讨论】:

  • 也许你需要在问之前单独考虑一下?用笔和纸试试,你会怎么做?
  • 我在计算重复次数超过 2 次的重复项时遇到问题。我只需要计算一次重复元素。例如,元素 1 出现了 3 次,但实际上是重复的。
  • for(int i=0;i
  • 这仅适用于数组中的元素重复 2 次。

标签: java arrays if-statement for-loop duplicates


【解决方案1】:

在数组中插入元素之前,首先检查数组的内容。如果插入对象等于 any 则不继续插入。

或者试试这个:

int[] arrayObject={1,5,7,4,5,1,8,4,1};
List<Integer> uniqueList=new LinkedList<>();
List<Integer> duplicateList=new LinkedList<>();
for(int i=0; i<arrayObject.length; i++){
    if(!uniqueList.contains(arrayObject[i])){
        uniqueList.add(arrayObject[i]);
    }else if(!duplicateList.contains(arrayObject[i])){
        duplicateList.add(arrayObject[i]);
    }
}
System.out.println("Elements without duplicates: "+uniqueList);
System.out.println("Duplicated elements: "+duplicateList);

输出:
没有重复的元素:{1、5、7、4、8}
重复元素:{1、5、4}

【讨论】:

  • 是的,我在纸上写了这个逻辑,但是在 java 代码中实现它时遇到问题。我卡在 for 循环的某个地方。
  • Tnx MarionJeff 寻求帮助
  • 点击星号接受它作为官方答案
猜你喜欢
  • 2015-08-31
  • 1970-01-01
  • 2011-04-26
  • 2019-04-27
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多