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
-
3Maybe you need to think about this alone before asking? Try with a pen and paper, what would you do?Alexis C.– Alexis C.2014年11月29日 12:39:57 +00:00Commented Nov 29, 2014 at 12:39
-
I have problem counting duplicates that are repeated more than 2 times. I need to count duplicate element only one time. For exemple, element 1 appears 3 time but in fact it is one duplicate.Dacha– Dacha2014年11月29日 12:42:33 +00:00Commented Nov 29, 2014 at 12:42
-
for(int i=0;i<array.length;i++) for(int j=i+1;j<array.length;j++) if(array[i]==array[j]) dupelement++;Dacha– Dacha2014年11月29日 12:47:21 +00:00Commented Nov 29, 2014 at 12:47
-
This only works if elements in arrays repeats 2 times.Dacha– Dacha2014年11月29日 12:48:33 +00:00Commented Nov 29, 2014 at 12:48
1 Answer 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}
answered Nov 29, 2014 at 12:44
-
Yes, I write that logic on paper but I have problem implement it in java code. I stuck somewhere in for loop.Dacha– Dacha2014年11月29日 12:51:25 +00:00Commented Nov 29, 2014 at 12:51
-
-
Accept it as the official answer by clicking the starmarion-jeff– marion-jeff2014年11月29日 13:33:41 +00:00Commented Nov 29, 2014 at 13:33
Explore related questions
See similar questions with these tags.
lang-java