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: 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; }}更新:可以使用 std :: unordered_multiset ,因为我们不需要订购.Update: Could use std::unordered_multiset, as we don't need ordering. 这篇关于如何从vector中删除重复项的所有实例int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-16 00:07