使用c++在数组中查找不同的元素
find distinct elements in an array using c++
我有一个整数数组。我想用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背后的基本思想
相关文章:
- 使用堆查找第K个最大元素的时间复杂性
- 查找矩阵C++中每一列和每一行的最小和最大元素
- C++如何在向量中查找最常见的元素
- 查找两个排序向量中共有的元素
- 在对向量中查找元素的索引
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 查找矩阵中单元格的相邻元素
- 为什么使用数组元素查找最大数字的程序不起作用?
- 查找第一个数组中不存在的元素
- 查找最小的下一个更大的元素
- 在最小堆中查找最大元素
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- set::find 查找不存在的元素
- 在集合中查找使用结构C++的元素
- 从斐波那契序列 c++ 中的数组中查找正确的元素时出错
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 查找数组中指示性较大但数组中值较小的元素
- C++结构集无法按元素查找/擦除
- 如何在OpenCV中使用Matlab的512元素查找表数组?
- 使用数组的元素查找总和'k'