Learn-dsa..in 30 days!



























CC-1 : Remove Duplicates.

Description:

Given an array containing some duplicated elements, remove the duplicates and return and array containing only unique elements.

Test cases and expected outputs:

Input Parameters Expected outputs
arr[]={ 1.0, 4.6, 8.1, 3.7, 4.60, 1}; 1.0,8.1,4.6,3.7
arr[]={ 7.2, 8.0, 5,3}; 8.0,7.2,5.0,3.0

Pseudocode:

The java method should accept following input parameters: arr (double array).
Initialize a variable set of type HashSet to hold the input elements.
Using a for loop iterate through arr, using idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
oAdd add[idx] to set.
After completion of above loop set contains the unique elements from arr, as HashSet only contains unique elements.
Use an iterator to access elements from set and add the same to double array named retVal. Return retVal.

Code:

public class SetArrayRemoveDuplicates {
	
public double[] setArrayRemoveDuplicates(double[] arr) {
	HashSet<Double> set=new HashSet<Double>();
	for (int idx=0; idx <arr.length; idx++) {
		set.add(arr[idx]);
	}
	double retVal[]=new double[set.size()];
	int idx=0;
	Iterator<Double> itr=set.iterator();
	while (itr.hasNext()) {
		retVal[idx]=itr.next().doubleValue();
		idx++;
	}
	return retVal;
}

Click here to download and run code and test cases !