import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class DuplicateNumbersInArray {
public static void main(String args[]){
int a[]={1,2,3,4,5,6,6,4,4,3,3};
System.out.println("Duplicate elements in Array"+dupElementsUsingSet(a));
}
private static ArrayList<Integer> dupElementsUsingSet(int[] a) {
ArrayList<Integer> arr=new ArrayList<Integer>();
Set<Integer> sortset=new HashSet<Integer>();
for(int i=0;i<a.length;i++){
if(sortset.contains(a[i]))
arr.add(a[i]);
else
sortset.add(a[i]);
}
return arr;
}
}
Have you check your output? This program output shows: Duplicate elements in Array[6, 4, 4, 3, 3]
ReplyDeleteThat is incorrect, since the number 6 is only printed once here when there is two number 6 in the original array.