This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
One way would be to add the contents of the array into a Set, then use the toArray() method to get it back out, now without duplicates.
Another way would be to create a second Array as large as the first array, take each value out of the source, loop over the values in the second and if the values doesn't already exist put it in the second array and increment a counter. Then create a third array using the counter to determine its size and copy values from the second array into the third. This process could be made faster if the values are sortable by first sorting the source array (for the least number of comparisons).
I would suggest a combination of those two methods. Use a second array, and add each element if it has not already been added. Use the set to maintain those already added. That will run in linear time, whilst using an array on its own runs in quadratic time. Using a Set in tandem with a List (maybe this) will probably allow you to do the whole thing in linear time, and maintain ordering, too.
Joined: Apr 30, 2012
First take one empty array. Now we need add the elements in first array to second array .Now take for loop and inside the for loop, write 'if' condition. In each iteration we need to add the elements into empty/second array. Before adding the element we need to check the element existence in the second array i.e in which we are adding elements.
If the element exists then we do nothing, else we add the element to the second array.