Tuesday, 15 March 2016

Write a program to remove duplicates from array

public class RemoveDuplicates {

public static Integer[] removeDuplicates(Integer[] input) {

Arrays.sort(input);
System.out.println("Sorted Array --->> " + Arrays.toString(input));
int i = 1, j = 0;
// return if the array length is less than 2
if (input.length < 2) {
return input;
}
while (i < input.length) {
if (input[i] == input[j]) {
i++;
} else {
input[++j] = input[i++];
}
}
Integer[] output = new Integer[j + 1];
for (int k = 0; k < output.length; k++) {
output[k] = input[k];
}

return output;
}

public static HashSet<Integer> removeDuplicatesUsingHashSet(Integer[] input) {
HashSet<Integer> hs = new HashSet<Integer>(Arrays.asList(input));
return hs;
}

public static void main(String[] args) {
Integer[] array = { 6, 7, 6, 8, 9, 10, 5, 4, 10, 11, 12, 12, 2, 3, 1 };
// remove duplicates from array
Integer[] output = removeDuplicates(array);
for (int i : output) {
System.out.print(i + " ");
}

System.out.println();
// remove duplicates from array using hashset
Set<Integer> set = removeDuplicatesUsingHashSet(array);
System.out.println("By Using HashSet --->> " + set);
}

}


Output:

Sorted Array --->> [1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10, 10, 11, 12, 12]
1 2 3 4 5 6 7 8 9 10 11 12 

By Using HashSet --->> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]