Attempting to determine if a vector contains a duplicate. This applies to the absolute value of the elements in the vector. I have tested my implementation with a few cases and have gotten inconsistent results.
bool has_duplicate(vector<int> v) {
vector<int>::iterator it;
for (it = v.begin(); it != v.end(); ++it) {
if (v[*it] < 0)
v[*it *= -1;
if (count(v.begin(), v.end(), v[*it]) > 1)
return true;
}
return false;
}
vector<int> v1 {1, -1} // true
vector<int> v3 {3, 4, 5, -3} // true
vector<int> v2 {2, -2} // false
vector<int> v4 {3, 4, -3} // false
vector<int> v5 {-1, 1} // false
Any insight on the erroneous implementation is appreciated
Aucun commentaire:
Enregistrer un commentaire