给定一个STL向量,输出排序后的重复项,例如:
INPUT : { 4, 4, 1, 2, 3, 2, 3 }
OUTPUT: { 2, 3, 4 }
这个算法很简单,但目标是使其效率与std::unique()一样高。我天真的实现直接在容器中进行修改:
我天真的实现:
void not_unique(vector<int>* pv)
{
if (!pv)
return;
// Sort (in-place) so we can find duplicates in linear time
sort(pv->begin(), pv->end());
vector<int>::iterator it_start = pv->begin();
while (it_start != pv->end())
{
size_t nKeep = 0;
// Find the next different element
vector<int>::iterator it_stop = it_start + 1;
while (it_stop != pv->end() && *it_start == *it_stop)
{
nKeep = 1; // This gets set redundantly
++it_stop;
}
// If the element is a duplicate, keep only the first one (nKeep=1).
// Otherwise, the element is not duplicated so erase it (nKeep=0).
it_start = pv->erase(it_start + nKeep, it_stop);
}
}
如果你能让这个更加高效、优雅或通用,请让我知道。例如,自定义排序算法,或在第二次循环中复制元素以消除erase()调用。
keep_duplicates(0)
也不安全)。函数内部的代码和调用函数都会简化一些。 :) - GManNickGerase
,使其变成了O(n^2)。 - James McNellis