在数组中查找出现至少3次的最频繁元素

时间:2018-10-05 15:20:09

标签: c arrays

我正在编写一个代码,以按固定大小 4个数组的形式打印出最频繁出现的数字,该事件至少出现3次 。

例如:

int arr[4] = {9,2,9,9}
Number that occurs at least 3 times is: 9

int arr[4] = {9,9,9,9}
Number that occurs at least 3 times is: 9

int arr[4] = {-1,3,3,3}
Number that occurs at least 3 times is: 3

int arr[4] = {9,-1,9,9}
Number that occurs at least 3 times is: 9

int arr[4] = {1,1,2,2}
Number that occurs at least 3 times is: None

我尝试过:

int arr[4] = {9,2,9,9};
int i;
int count;
int value;
int first;

int length = sizeof(arr) / sizeof(int);
int count = 0;
for (i=1;i<length-1;i++) {
    first = arr[0];
    if (first == arr[i]) {
        value = arr[i];
        count +=1;
    }
}
if (count >= 3) {
    printf("Number that occurs at least 3 times is: %d",value);
}
else {
    printf("Number that occurs at least 3 times is: None");
}

但是我得到了输出:

Number that occurs at least 3 times is: None

应该是:

Number that occurs at least 3 times is: 9

我错过了什么?希望对此有所帮助。

2 个答案:

答案 0 :(得分:1)

因为您的for循环仅运行2次,计数最多为2。

答案 1 :(得分:0)

首先,您必须修复循环以比较最后一个元素:

for (i=1;i<length;i++) {
    ...
}

但是,如果找不到元素,则第一个元素可能不包含最频繁的数字,而其他三个元素却包含。因此,您必须检查其他三个数字是否相同:

if (count >= 3) {
    printf("Number that occurs at least 3 times is: %d",value);
} else if (arr[1] == arr[2] && arr[1] == arr[3])
    printf("Number that occurs at least 3 times is: %d",arr[1]);
} else {
    printf("Number that occurs at least 3 times is: None");
}

这应该涵盖所有情况。