Reputation: 87
Below is a block of code from leetcode, I'm wondering what does the second line mean. I never saw this kind of initializing set. Could anyone help? Thank!
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s (nums.begin(), nums.end());
return s.size()!=nums.size();
}
Upvotes: 0
Views: 794
Reputation: 73304
unordered_set<int> s (nums.begin(), nums.end());
This initializes the set by iterating over the specified vector
, starting at the beginning of the vector and iterating until it reaches the end, calling s.insert(theVal)
for each int
in the vector
.
return s.size()!=nums.size();
Since an unordered_set
, by its nature, does not allow any duplicate keys to exist in the set (i.e. trying to insert a key into the set, while that key is already a member of the set, will not modify the set at all), then we know that if the final size of the set is less than the size of the input vector, that the input vector must have had at least one duplicate value in it.
Upvotes: 3