求众数
萌新,用了一下快排降低时间复杂度
#include<stdio.h>
#include<stdlib.h>
int cmp(const void *a, const void *b) {
return *(int *)a - *(int *)b;
}
int main()
{
int numbers[10] = {2,3,1,2,3,4,5,6,1,8};
int counts[10] = {0}, sum[10] = {0}; // sum存储对应下标众数, counts存储对应次数
int max = 0;
qsort(numbers, 10, sizeof(numbers[0]), cmp);
int left = 0, right = 1, count = 0;
while(right < 10) {
if(numbers[left] == numbers[right]) {
right ++;
sum[count] = numbers[left];
counts[count] = right - left;
if(max < counts[count])
max = counts[count];
} else {
left = right;
right ++;
count ++;
}
}
if(max == 0)
printf("no zhongshu.");
else {
for(int i = 0; i < count; i ++) {
if(counts[i] == max) {
printf("%d个%d\n", counts[i], sum[i]); // 输出表示有counts[i]个sum[i]
}
}
}
//printf("%d\n", max);
//printf("%d", count);
return 0;
}
随手写的,凑合凑合