To determine if an array contains duplicate elements, we can use a 'set' data structure. A
set
automatically
eliminates duplicate values
, so by
inserting all elements
of the
array into the set, we can
compare the size
of the set with the
size of the original array. If the
sizes differ
, it means there were
duplicates in the array.
class Solution { public: bool containsDuplicate(vector<int>& nums) { set<int> st(nums.begin(),nums.end()); return st.size() != nums.size(); } };
The algorithm inserts all elements of the array into a set, which takes O(n) time, where 'n'
is the number of
elements in the array. Checking the size of the set is a constant-time operation.
The set stores at most
'n'
elements, where
'n'
is the size
of the input array.
In the worst case, if all
elements are unique, the set will store all 'n'
elements.