使用双阵列查找模式

Using double arrays to find the mode?

本文关键字:查找 模式 阵列      更新时间:2023-10-16

我使用该数组中包含的一组整数的模式或模式,使用该数组及其长度作为参数。我在网上找到了有关如何找到数组模式的多个解决方案,但是我正在尝试通过以下方式解决此问题:

假设原始数组包含(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