Friday, July 10, 2015

How to find duplicates in a list of number

I was trying to find out all the ways I can detect a duplicate in a list of numbers using the C++ Standard Library

Method 1
Use the fact that set does not allow duplicate numbers

bool containsDuplicate(vector<int>& nums)
{
bool DuplicateFlag = false;
set<int> s;
int previousSize = 0;

for (int index = 0; index < nums.capacity(); index++)
{
s.insert(nums[index]);
if (s.size() == previousSize)
{
DuplicateFlag = true;
break;
}
previousSize = s.size();
}

return DuplicateFlag;
}

No comments:

Post a Comment