How to find duplicates in a java array using only for, if or while?

久未见 提交于 2019-12-12 06:02:28

问题


can someone explain me how to find duplicate elements in java: array {1,5,7,4,5,1,8,4,1} using only for, if or while/do while?

Tnx in advance.

Dacha


回答1:


Before you insert an element in the array, check first the content of the array. If the inserting object is equal to any then do not proceed with the insert.

Or maybe try this one:

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);

Output:
Elements without duplicates: {1, 5, 7, 4, 8}
Duplicated elements: {1, 5, 4}



来源:https://stackoverflow.com/questions/27202325/how-to-find-duplicates-in-a-java-array-using-only-for-if-or-while

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!