第3 题不会,用c怎么做

这道题不会,用c怎么做

img

可以参考下,

#include <stdlib.h>
#include <stdio.h>

/**
 * 将a[0..size-1]中出现次数最多的数字, 存放到res[0..*resSize - 1], 可能会改变*resSize值, 
 * (*resSize)代表实际出现次数最多的数字个数
 */
void countNum(int a[], int size, int *pRes, int *resSize)
{
    if (size <= 0) return;
    int map[10] = { 0 }; // 数字0~9出现次数
    int max_counter = 0; // 最大次数

    // 统计a[0..size-1]各数字出现次数, 并求出出现次数最大值
    for (int i = 0; i < size; i++) {
        // 统计a[i]各数字出现次数
        while (a[i] > 0)
        {
            int d = a[i] % 10;
            map[d]++;
            max_counter = max_counter < map[d] ? map[d] : max_counter;

            a[i] /= 10;
        }
    }
    
    if (!resSize) return;
    /* 确保pRes指向空间有足够空间存放10个数字 */
    if (*resSize < 10) {
        pRes = (int *)realloc(pRes, 10);
    }

    int i, k;
    for (i = 0, k = 0; i < 10; i++) { // 0~9 共10个数字
        if (map[i] == max_counter) {
            pRes[k++] = i;
        }
    }
    *resSize = k;
}

int main()
{
    int a[] = { 1234, 2345, 3456 };
    int size = sizeof(a) / sizeof(a[0]);
    int res[10];
    int res_len = sizeof(res) / sizeof(res[0]);
    countNum(a, size, res, &res_len);

    for (int i = 0; i < res_len; i++) {
        printf("%d ", res[i]);
    }

    fflush(stdout);
    return 0;
}