前言
利用C++简单实现统计数组中出现频次最多的元素与数组中前,n大元素,例如[1,2,3,3,4,4,4,5]中,出现频次最多的元素为4,前三大元素为3、4、5。
C++实现
#include <iostream>
#define N 10
using namespace std;
typedef int ElemType;
void getIndex(ElemType *array, ElemType *array_count){
ElemType temp_array[2 * N]= {
0};
int index = 0, j = 0, end = 0;
int max_count = array_count[0];
for(int i = 0; i < 2 * N; i ++){
if(array_count[i] == 0)
break;
if(array_count[i] >= max_count)
max_count = array_count[i];
}
for(int i = 0; i < 2 * N; i++){
if(array_count[i] == 0) {
end = i;
break;
}
if(array_count[i] == max_count) {
for (int k = 0; k <= i; k++)
index += array_count[k];
temp_array[j++] = index - 1;
index = 0;
}
}
cout << "The most frequent element: ";
for(int i = 0; i < 2 * N; i++){
if(temp_array[i] == 0) {
break;
}
cout << array[temp_array[i]] << " ";
}
cout << endl << "The first three elements: ";
for(int i = end; i > end - 3; i--){
index = 0;
for(j = 0; j < i; j++)
index += array_count[j];
cout << array[index-1] << " ";
}
}
// 获取出现频次最多的元素与前三大元素,可能存在多个相同频次的元素
void elementCount(ElemType *array){
ElemType temp = array[0];
ElemType array_count[2 * N] = {
0};
for(int i = 0, j = 0; i < 2 * N; i ++){
if(array[i] == temp)
array_count[j]++;
else{
array_count[++j]++;
temp = array[i];
}
}
getIndex(array, array_count);
}
int main(){
ElemType array[N] = {
0,1,2,4,4,7,7,7,7,9};
elementCount(array);
return 0;
}