0

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

4
  • 3
    Maybe you need to think about this alone before asking? Try with a pen and paper, what would you do? Commented 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. Commented 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++; Commented Nov 29, 2014 at 12:47
  • This only works if elements in arrays repeats 2 times. Commented Nov 29, 2014 at 12:48

1 Answer 1

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}

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I write that logic on paper but I have problem implement it in java code. I stuck somewhere in for loop.
Tnx MarionJeff for help
Accept it as the official answer by clicking the star

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.