Search code examples
c++algorithmvectordata-structuresstdvector

How to remove all instances of a duplicate from a vector<int>


I've been trying to solve an "easy" leetcode question for two hours now where I need to remove every instance of an int that appears more than once then add the non dupes together. I've tried about 10 different ways and I can only get it to go down to one copy of each int. Here is the nicest solution I've written, but given input {1,2,2,3,4} it would return {1,2,3,4} whereas the expected output is {1,3,4}

  sort(nums.begin(), nums.end()); //Sort numerically
  nums.erase(unique(nums.begin(), nums.end()), nums.end()); 
  return (accumulate(nums.begin(), nums.end(), 0)); 

Solution

  • NlogN complexity, you avoid needing to pre-sort:

    Godbolt

    #include <set>
    #include <vector>
    
    int main()
    {
        std::vector<int> nums = {1,2,2,3,5};
    
        std::multiset<int> m (nums.begin(), nums.end());
    
        std::size_t sum = 0;
        for (const auto& elem : m)
        {
          sum += m.count(elem) == 1 ? elem : 0;
        }
    }
    

    Update: Could use std::unordered_multiset, as we don't need ordering.