使用c++在数组中查找不同的元素

find distinct elements in an array using c++

本文关键字:元素 查找 c++ 数组 使用      更新时间:2023-10-16

我有一个整数数组。我想用c++找到数组中所有不同的元素。解决方案1:蛮力使用嵌套循环,该解的复杂度为O(n^2)

解决方案2:排序这将花费O(nLog n)

是否有其他技术可以提供比O(n Log n)更好的结果?还有其他的数据结构或技术吗?

使用std::unordered_set将是O(n)。

您也可以尝试使用std::nth_element:它对范围[first, n-th, last]进行部分排序,使得区间[first, n-th]中的所有条目都是<= n-th,并且区间(n-th, last)中的所有元素都>=> n-th。它具有线性复杂度(O(n)),并将找到序列中的第n个元素。但是,找一个具体的数字是不合适的,所以它可能不是你真正需要的。但值得记住:-)

如果您知道最大整数,并且它相当小,则可以分配一个大向量,并使用它来计算每个整数的频率。然后,遍历向量并找到频率为1的所有向量:

template<typename I>
auto findWithFrequency(int f, int max, I first, I last)
{
    std::vector<int> counts(max, 0);
    for(; first != last; ++first)
    {
        counts[*first] += 1;
    }
    std::vector<typename I::value_type> v;
    v.reserve( std::distance(first, last) );
    std::copy_if(counts.begin(), counts.end(),
                 std::back_inserter(v),
                 [f](auto x) {return x == f;});
    return v;
}

在最坏的情况下,这需要对输入数组大小的数组进行两次迭代,因此复杂度为O(n)。

这就是Bucketsort或Radix背后的基本思想