Even though lots of people posted code here, I believe that the best approach to help on such a problem is to actually explain what data structure needs to be used and also what’s the underlying idea if you don’t know such data structure.
The basic idea here, is that you have a certain list, let’s call it S’ such that it contains several duplicate elements.
So, for instance:
S’ = [1,4,5,6,2,4,3,2,1]
The basic idea to solve your problem easily could be to create an auxiliar array, that will hold only the distinct elements that are on the original set. Let this list be called Aux. So:
Aux = [1,4,5,6,2,3]
This auxiliar data structure can be constructed in the following manner:
-
Initially, it is empty:
Aux = []
-
Append 1st element of S’ to it:
Aux = [1]
-
Check if the 2nd element of S’ is equal to the 1st one already in Aux:
3.1 If it is, advance to next element, leaving Aux unchanged;
3.2 If it is not, append it to Aux, and advance to next element;
-
Repeat procedure 3 until you’ve reached the end of S’.
The complexity of such approach is O(N^2), but we can do much better than this…
It turns out, that a data structure exists, called a Set, which is, completely similar to its mathematical twin, especially in the sense that it can’t contain any duplicate elements and the elements on a given set are always ordered… More info on sets, [here][1].
It is relatively easy to implement such a data structure since it is built-in on the vast majority of programming languages
As a reference, here is a Python code, that removes all duplicate elements from a list:
L = [1,3,3,5,6,7,1,5,4,4,16,8,6]
print list(set(L))
The above code will return the list: [1,3,4,5,6,7,8,16]
Note that sets are immutable, so you can’t change a set directly, that’s the reason I converted it back into a list on my code… Hope I could help you out
[1]: http://en.wikipedia.org/wiki/Set_(mathematics)