4.Find the Duplicate Number
Example 1:
Input: nums = [1,3,4,2,2]
Output: 2
Example 2:
Input: nums = [3,1,3,4,2]
Output: 3
Example 3:
Input: nums = [1,1]
Output: 1
Example 4:
Input: nums = [1,1,2]
Output: 1Solution: (Using Hashset)
class Solution
{
public:
int findDuplicate(vector<int> &nums)
{
unordered_set<int> s;
for (int i = 0; i < nums.size(); i++)
{
if (s.find(nums[i]) == s.end())
{
s.insert(nums[i]);
}
else
{
return nums[i];
}
}
return -1;
}
};Solution II : Floyd's Tortoise and Hare (Cycle Detection)

Last updated