我正在努力从头开始使用 C 语言,并确保在继续学习之前了解所有细节。今天,我的目标是编写一个程序,该程序将接受一个整数列表(假设少于 50 个整数),并打印一个表格,其中一侧是唯一整数列表,另一侧是它出现的次数。我有一个函数的副本,它负责计算它出现的次数。
我的函数的快速总结:接受 2 个指向数组的指针,以及一个要迭代多少个整数的整数。假设:我们正在检查某个数字 x 的重复。在数组的某个地方,我们点击了另一个 x。它增加 x 的计数并将 x 变为 0 以供以后使用。
样本试验 输入:1 2 1 2 2 1 2 输出:1 出现 3 次。 2 出现了 4 次。
输入:1 2 3 1 2 3 1 2 3 输出:1 出现 3 次。 2出现3次。 3 出现 3 次。
输入:1 2 1 3 1 2 3 输出:1 出现 3 次。 2出现2次。 3出现1次。
虽然该程序大部分都在运行,但我想确保它完全运行。因此,我的问题是最后一次审判。为什么 3 在适用于其他 2 个输入集时只被读取一次?
void countOccurrences(int *list, int size, int *uniques){
for (int i = 0, t = 0; i < size; i++){
int temp = list[i];
if (temp == 0){ //If the number was a repeat of another previous number
continue; //skip over it and go to the next element in list
}
uniques[t] = 1;
for (int j = i+1; j <= size; j++){ //this iterates through list for any repeats of temp
if (temp == list[j]){ //All repeats of temp turn to 0
uniques[i]++;
list[j] = 0;
}
}
t++;
}
}
最佳答案
这是因为,3 作为最后一个数字,您将出现次数重置为 1
uniques[t] = 1;
并且 for 循环根本不运行,因为那是最后一个数字,您没有在数组中回头看。
我会简单地写这个程序如下。给定的列表有值 >=0
for (int i = 0; i < size; i++){ //this iterates through list for any repeats of temp
uniques[list[i]]++;
}
对于具有任何值的列表,使用 hash table数据结构
关于计算每个唯一数字的出现次数 : algorithm almost works,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22391513/