Last active
March 18, 2022 05:51
-
-
Save tannerdolby/f8c0e068e6360a7c20602a15ed7fb079 to your computer and use it in GitHub Desktop.
A template function to check a std::vector<T> for duplicate values.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// O(n) time and O(n) space where n = length of the input sequence | |
template <typename T> | |
bool containsDuplicate(std::vector<T> &sequence) { | |
std::unordered_set<T> uset; | |
for (auto val : sequence) { | |
if (uset.count(val) > 0) { | |
return true; | |
} | |
uset.insert(val); | |
} | |
return false; | |
} | |
// Usage | |
std::vector<int> vec1; | |
vec1.push_back(1); | |
vec1.push_back(3); | |
vec1.push_back(1); | |
// 1 3 1 | |
std::cout << containsDuplicate(vec1) << std::endl; // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Building on the above, we could have a struct or some other user defined data structure to represent each duplicate and store information about where the duplicate occurred.