【问题标题】:Error in algorithm to find the most repeating element in an array查找数组中重复次数最多的元素的算法错误
【发布时间】:2022-01-10 03:16:32
【问题描述】:

我的任务是在没有排序或哈希表的情况下找到数组中重复次数最多的元素。

这是我的伪代码:

#include <stdio.h>
  
int most_frequent(int *a, int n)
{
    int i, j, max_element, count;
    int maxcount = 0;

    for(i = 0; i<n; i++)
    {
        count = 1;
        for(j = i+1; j<n; j++)
        {
            if(a[j] == a[i])
            {
                count ++;
                if(count > maxcount)
                {
                    max_element = a[j];
                }
            }
        }
    }
    return max_element;
}

问题是,它并不总是能正常工作,例如使用数组[1 1 2 2 3 3 3 4 4 4 4 5 5 7],结果将是5

【问题讨论】:

  • 最大计数永远不会改变

标签: arrays c algorithm frequency function-definition


【解决方案1】:

在这个if语句中

            if(count > maxcount)
            {
                max_element = a[j];
            }

您忘记更改变量 maxcount

            if(count > maxcount)
            {
                maxcount = count;
                max_element = a[j];
            }

此外,if 语句应移至内部 for 循环下方。

for(i = 0; i<n; i++)
{
    count = 1;
    for(j = i+1; j<n; j++)
    {
        if(a[j] == a[i])
        {
            count ++;
        } 
    }

    if(count > maxcount)
    {
        maxcount = count;
        max_element = a[i];
    }

}

请注意,如果用户将参数 n 的值传递给函数等于 0,那么函数将返回一个不确定的值,因为变量 max_element 未初始化。

这样定义函数会更好,因为它返回出现频率最高的元素的索引,如下面的演示程序所示

#include <stdio.h>

size_t most_frequent( const int *a, size_t n )
{
    size_t pos = 0;
    size_t max_count = 0;
    
    for ( size_t i = 0; i < n - max_count; i++ )
    {
        size_t count = 1;
        for ( size_t j = i + 1; j < n; j++ )
        {
            if ( a[j] == a[i] ) ++count;
        }
        
        if ( max_count < count )
        {
            max_count = count;
            pos = i;
        }
    }
    
    return pos;
}

int main( void ) 
{
    int a[] = { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 7 };
    const size_t N = sizeof( a ) / sizeof( *a );

    size_t pos = most_frequent( a, N );
    
    printf( "The most frequent number is %d found at position %zu\n", 
            a[pos], pos );  

    return 0;
}

程序输出是

The most frequent number is 4 found at position 7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 2014-04-19
    • 2015-06-07
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    相关资源
    最近更新 更多