繁体   English   中英

如何返回数组中出现频率最低的整数?

[英]How to return the integer with the lowest value that occurs the most frequently in an array?

我设法编写了代码来返回出现最多的数字,但是当多个数字出现的次数相同时,我需要返回具有最低值的那个。

int getFreq(int arg) {

    int tmp;
    int storage[10] = { 0 };
    int maxDigit = -1;
    int maxfreq = -1;

    tmp = (arg < 0) ? -arg : arg;

    do {

        storage[tmp % 10]++;

        if (storage[tmp % 10] > maxDigit) {

            maxDigit = storage[tmp % 10];
            maxFreq = tmp % 10;

        }

        tmp /= 10;

    } while (tmp != 0);

    return maxFreq;
}

我修改了您的函数,并将统计信息收集与其分析分开,以便轻松找到最频繁但最低的数字。 6 和 7 都出现了两次。 7 的括号括住所显示数字中的 6,但该函数返回 6。

#include <stdio.h>

int getFreq(int arg) {
    int tmp;
    int storage[10] = { 0 };
    int maxFreq = -1;
    int digit = 0;

    tmp = (arg < 0) ? -arg : arg;
    do {
        storage[tmp % 10]++;
        tmp /= 10;
    } while (tmp);

    for (tmp=9; tmp>=0; tmp--) {
        if (storage[tmp] >= maxFreq) {
            digit = tmp;
            maxFreq = storage[tmp];
        }
    }
    return digit;
}

int main(void)
{
    int val = 17266375;
    printf("Most frequent (lowest) from %d = %d\n", val, getFreq(val));
    return 0;
}

程序输出:

Most frequent (lowest) from 17266375 = 6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM