I know that set doesn't contain duplicates, but it sorts the elements. I want a data structure that doesn't sort the elements and doesn't contain duplicates.
For example if the data structure contains ints,
Input: 5 4 1 2 5 4 9
Elements in data structure
5 4 1 2 9
Please help.
in Java, you can use a
LinkedHashSet
in any language, you can do it yourself using a
list
(orvector
) and aset
in combinationWhy not use a
HashSet
? Is it faster?When using the hashset the elements will be sorted and will lose order of element
I think you're thinking of the
TreeSet
which maintains elements in order. TheHashSet
does not. I was just asking if there was any specific reason for aLinkedHashSet
over theHashSet
(e.g. faster time, less memory, etc)Qualified said they didn't want to sort the elements, and technically HashSet doesn't. But I assume they actually meant they want to maintain the original order, and HashSet doesn't do that either. LinkedHashSet is exactly the same as HashSet except it also stores the original insertion order for iteration.
Sorry for mistake in the first time!
You can use map to check if the element in the array or not and a vector array to save the elements.
And again sorry for my bad English!
When I put in the elements in the unordered set it outputs 2 1 5 9 4 and not 5 4 1 2 9
Just do hashmap such that if for each x if mp.count(x) then skip else mp[x] = 1
P.S. I see no reason for downvotes in this blog just because of his rating
As said above, you can actually use two data structures for the two properties you desire: one will maintain the order (
vector
withpush_back
), and the other will check for duplicates before inserting (set
orunordered_set
). Code for insertion will be something like this: