Learn-dsa..in 30 days!



























CC-3 : Remove Duplicates from list and preserve sequence of remaining.

Description:

Given an array containing duplicate elements, remove the duplicates and preserve the sequence of 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,4.6,8.1,3.7
arr[]={ 7.2, 8.0, 5,3}; 7.2,8.0,5.0,3.0

Pseudocode:

The java method should accept following input parameters: arr (double array).
Initialize a variable set of type LinkedHashSet 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:
Add arr[idx] to set.
At completion of above loop, set contains all the unique elements from arr with input/original order preserved for the remaining unique elements.
Use an iterator to access elements from set and add the same to double array named retVal. Return retVal.

Code:

public double[] setArrayRemoveDuplicatesPreserveOrder(double[] arr) {
	LinkedHashSet<Double> set=new LinkedHashSet<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 !