0

Possible Duplicate:
Java Array, Finding Duplicates

arr=[3,4,1,2,1,5,2]

How do i find the duplicates in this array and then return the duplicates in an array?

In the case the result should be result [1,2]

I am programming in Java.

Community
  • 1
  • 1
  • 5
    Is this homework? What have you done so far? – kosa Jul 30 '12 at 21:43
  • show us some code and the issues you are dealing with. – maasg Jul 30 '12 at 21:50
  • We won't solve the problem for you. But if you are stuck trying to do something, we can help. What have you tried? What hasn't worked? – Ruan Mendes Jul 30 '12 at 21:54
  • Do you want the strategy or the code? Try developing a strategy on your own. It will be similar to how you would do the same task, if asked to be done manually. – Vikram Jul 30 '12 at 21:58

2 Answers2

1

I recommend taking the following steps:

1) Create a HashSeta. The HashSet will contain integers you have read.

2) Iterate through the entire array [0 ... size - 1]. Keep track of what index you are at with an index variable.

3) In each iteration, do a HashSet.contains(arr[index]) operation. If it is true, it is a duplicate. Save this integer somewhere. Add arr[index] to the set.

4) Return the HashSet as the result.

Chris Dargis
  • 5,891
  • 4
  • 39
  • 63
  • For this to work, you'd need 2 HashSets: one to keep track of numbers seen and another to store unique duplicates. You'd return the latter HashSet. – irrelephant Jul 31 '12 at 10:44
  • @Doug, "3) In each iteration, do a HashSet.contains(index) operation. If it is true, it is a duplicate. Save this integer somewhere." In this, by 'index' you mean the Object at the current location or the location itself? – Vikram Jul 31 '12 at 14:23
0

Use nested for loop. take the first element and compare it with all the array. and then send the duplicated ones to a new array by using if/else logic.

I am not giving a code block because it is tagged as homework.

ferit enişer
  • 41
  • 1
  • 8