如何从vector中删除重复项的所有实例int [英] How to remove all instances of a duplicate from a vector<int>
问题描述
我一直在努力解决简单"的问题.leetcode问题两个小时了,在这里我需要删除一个或多个出现多次的int实例,然后将非重复对象加在一起.我尝试了大约10种不同的方法,但只能将其简化为每个int的一个副本.这是我编写的最好的解决方案,但是给定输入{1,2,2,3,4},它将返回{1,2,3,4}而预期的输出为{1,3,4} >
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));
推荐答案
NlogN
的复杂性,您无需进行预排序:
NlogN
complexity, you avoid needing to pre-sort:
#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;
}
}
更新:可以使用 std :: unordered_multiset
,因为我们不需要订购.
Update: Could use std::unordered_multiset
, as we don't need ordering.
这篇关于如何从vector中删除重复项的所有实例int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!