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.

4
  • 5
    Is this homework? What have you done so far? Commented Jul 30, 2012 at 21:43
  • show us some code and the issues you are dealing with. Commented Jul 30, 2012 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? Commented Jul 30, 2012 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. Commented Jul 30, 2012 at 21:58

2 Answers 2

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.

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

2 Comments

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.
@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?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.