Saturday, August 18, 2012

Finding duplicate elements in given array using Set


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;
}
}

1 comment:

  1. Have you check your output? This program output shows: Duplicate elements in Array[6, 4, 4, 3, 3]

    That is incorrect, since the number 6 is only printed once here when there is two number 6 in the original array.

    ReplyDelete

Thanks for your valuable comments