C++ 使用双数组查找模式?

C++ 使用双数组查找模式?,c++,arrays,mode,C++,Arrays,Mode,我一直在研究如何编写一个函数来查找数组中包含的一组整数的模式,并使用该数组及其长度作为参数。我在网上找到了多种有关如何查找阵列模式的解决方案,但我正在尝试以下方式解决此问题: 假设原始数组包含(0,0,1,5,5,5,7,7,7)。我想用一个循环遍历数组,该循环在不存储模式的情况下查找任何数量中的最高频率,并将这些频率存储在另一个数组中,在这种情况下,新数组将具有值(1、2、1、1、2、3、1、2、3)。通过在第二个数组中找到最大值,我将找到最高频率,在本例中为3。然后我想再次遍历原始数组,将最

我一直在研究如何编写一个函数来查找数组中包含的一组整数的模式,并使用该数组及其长度作为参数。我在网上找到了多种有关如何查找阵列模式的解决方案,但我正在尝试以下方式解决此问题:

假设原始数组包含(0,0,1,5,5,5,7,7,7)。我想用一个循环遍历数组,该循环在不存储模式的情况下查找任何数量中的最高频率,并将这些频率存储在另一个数组中,在这种情况下,新数组将具有值(1、2、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;
              }
      }   
void findMode(int数组,int大小){
整数计数=1;
整数频率[大小];
频率[0]=计数;
对于(int pass=1;pass
如果您不介意一些额外的存储(可能是
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;
}

#include//prints 5:3

std::sort(array.begin(),array.end())
先把它们放在一起,然后迭代。使用一个以键为整数,以值为其出现点的映射如何。每次你再次看到同一个键时,增加值。尽管我不确定你如何从中确定最大值,除非你迭代整个过程。编辑:这个问题显示了同样的事情,只是保持一个运行的cou为什么不保留一个列表,其中的值等于列表中的最大值,如果发现一个值高于最大值,则将其擦除?