查询数组中出现次数最多的元素
#include <stdio.h> #include <malloc.h> #include <stdlib.h> int max_count_num(int * arr, int len); int main() { int arr[5] = {1, 1, 1, 3, 1 }; max_count_num(arr, 5); return 0; } int max_count_num(int * arr, int len) { int i, j; int m; int count; //定义次数存储数组 int * max = (int *)malloc(sizeof(int) * len); if (max == NULL) { printf("malloc failed\n"); exit(-1); } //数组初始化 for (i = 0; i < len; i++) { max[i] = 0; } //对数组中的元素进行count for (i = 0; i < len; i++) { count = 0; for (j = i; j < len; j++) { if (arr[i] == arr[j]) { max[i]++; } } } //取出数组中元素的最大值 m = 0; for (i = 0; i < len; i++) { if (max[m] < max[i]) { m = i; } } printf("出现次数最多的元素为:%d, 出现次数为:%d\n", arr[m],max[m]); return 0; }
原文地址:https://www.cnblogs.com/ykyk1229/p/9911734.html
时间: 2024-10-12 04:18:33