我需要找到一个数组的模式,我的教授告诉我们使用另一个数组来保持每个数字的重复。这是我的模式功能:
int mode(int *arr, int s)
{
int num = arr[0];
int mod = num;
int modeCount[s];
int countMode = 1;
for(int count = 1; count < s; count++)
{
if(arr[count] == num)
modeCount[count - 1]++;
else
{
if(modeCount[count] > countMode)
{
countMode = modeCount[count - 1];
mod = num;
}
}
num = arr[count];
}
return mod;
}
使用诸如{1、5、3、5}的数组,我的模式为3。
我还应该提到,如果有多种模式,我不必编码不同(教授说不用担心(,如果没有模式,我必须返回-1,因此此代码不完整。<<<<<<
有人对如何修复我的代码并使其正常工作有任何想法吗?
如果数组的元素受S的限制,则可以使用此想法。
int mode(int* arr, int s)
{
int count[s + 1] = {0}; // The size is s + 1, in case the elements on the array belong to the interval [0, S]
for(int i = 0; i < s; ++i)
count[arr[i]]++;
int best = 0;
int mode = -1;
int numberOfElementsTied = 0;
for(int i = 0; i < s; ++i)
{
if( count[i] > best)
{
best = count[i];
mode = i;
numberOfElementsTied = 1;
}
else if( count[i] == best)
{
numberOfElementsTied++;
}
}
if(numberOfElementsTied == 1) return mode;
else return -1;
}