使用双阵列查找模式
Using double arrays to find the mode?
我使用该数组中包含的一组整数的模式或模式,使用该数组及其长度作为参数。我在网上找到了有关如何找到数组模式的多个解决方案,但是我正在尝试通过以下方式解决此问题:
假设原始数组包含(0、0、1、5、5、5、7、7、7)。我想通过一个循环迭代数组,该循环在不存储模式的情况下找到任何数量的最高频率,然后将这些频率存储在另一个数组中,在这种情况下,新数组将具有值(1、2、1、1,1、2、3、1、2、3)。通过在第二个数组中找到最大值,我会发现最高频率,在这种情况下为3。然后,我想再次迭代原始数组,将最高频率与该数组中每个值的计数进行比较,而在有匹配的情况下,我返回该值,在此示例中是5和7给予。给定标准,您将如何编写此功能以查找给定数组的模式或模式?(您可以假设数组已经按升序排序了)。
编辑:这是我的初步代码。我要达到在原始数组中找到每个整数的频率并将它们存储到另一个数组中的步骤。
void findMode(int array, int size){
int count = 1;
int freq[size];
freq[0] = count;
for (int pass = 1; pass < size; pass++){
if (array[pass] == array[pass-1]){
count++;
freq[pass] = count;
}
else{
count = 1;
freq[pass] = count;
}
}
如果您不介意一些额外的存储(潜在的O(N)
存储),则可以使用std::map
获取计数,然后进行线性搜索最常见的数字。
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <map>
#include <vector>
template<class InputIterator>
auto mode(InputIterator first, InputIterator last)
{
using key_type = typename std::iterator_traits<InputIterator>::value_type;
std::map<key_type, std::size_t> counts;
for (auto it = first; it != last; ++it) {
counts[*it]++;
}
return *std::max_element(counts.cbegin(), counts.cend(), [](auto const& lhs, auto const& rhs) {
return lhs.second < rhs.second;
}); // return mode + frequency
}
int main() {
auto v = std::vector<int> { 0, 0, 1, 5, 5, 5, 7, 7, 7 };
auto m = mode(v.cbegin(), v.cend());
std::cout << m.first << ": " << m.second;
}
实时示例//打印5:3
相关文章:
- 在C++的一系列数字中查找重复模式
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 在数组中查找重复模式
- 在图像中查找相似的(大)模式
- 在C++中查找文本中的模式
- 扫描位数组以查找多个位的模式
- 在数组中查找模式的最有效方法?
- 为什么 POSIX 允许在现有文件末尾 (fseek) 之外查找只读模式
- 编写模式识别'函数以查找特定顺序出现的数字?C++
- 查找模式C++
- 从列表到数组C 查找模式或最常见的数字
- 使用双阵列查找模式
- 查找整数中的重复模式
- 查找未排序数组的模式,以及该数组是否具有多个模式或无模式
- 如何通过将数组的指针传递给函数来查找数组的模式?C++
- 使用 bin 搜索查找排序数组的模式
- 在数组中查找一个或多个模式
- 如何在虚幻编辑器内容浏览器中查找虚幻游戏模式
- 在具有重复项的长数据序列的滚动窗口中查找模式
- 在字符串正则表达式c++中查找模式