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