数组去重时count计数翻倍问题求助及代码排查
数组去重计数错误问题分析与修复
题目要求将数组int zahlen[]={1,4,5,1,5,7,9,2,3,4}中的重复元素替换为-1,每完成一次替换就将变量count加1。但实际运行后,count值是预期的两倍——案例中实际有3个重复元素,count却显示6。相关代码如下:
#include <stdio.h> #include <stdlib.h> int main() { system("chcp 1252"); int zahlen[]={1,4,5,1,5,7,9,2,3,4}; int len = sizeof(zahlen)/sizeof(int); int erg = array_unique(zahlen,len); printf("Es wurden %d doppelte Zahlen gelöscht: \n",erg); printf("Das Array hat nun folgende Werte: "); printArrayUnique(zahlen,len); return 0; } void printArrayUnique(int *array, int len){ for(int i=0; i<len; i++){ if(array[i]!=-1){ printf("%d ",array[i]); } } } int array_unique(int *array, int len){ int count=0; for(int i=0; i<len;i++){ for(int j=i+1; j<len;j++){ if(array[i]==array[j]){ array[j] = -1; count++; } } } return count; }
错误原因分析
核心问题是未跳过已标记为-1的元素:
- 当前代码的外层循环会遍历数组所有元素,包括已经被标记为重复的
-1元素。 - 当遍历到
-1元素时,它会和后面所有元素对比,而后面已经存在其他-1的标记元素,每一次相等都会触发count++,产生额外的无效计数。 - 举个具体例子:原数组中索引0的
1将索引3的1标记为-1后,后续遍历到索引3的-1时,会和索引4(已被标记为-1的5)、索引9(已被标记为-1的4)分别对比,这两次相等都会让count额外加1,最终导致计数翻倍。
修复方案
在array_unique函数的外层循环中,先判断当前元素是否为-1,如果是则跳过该元素的内层对比,避免用已标记的重复元素去触发无效计数:
int array_unique(int *array, int len){ int count=0; for(int i=0; i<len;i++){ // 跳过已经被标记为重复的元素,避免无效对比 if(array[i] == -1){ continue; } for(int j=i+1; j<len;j++){ if(array[i]==array[j]){ array[j] = -1; count++; } } } return count; }
修改后,只会用原数组中未被标记的有效元素去对比后面的元素,count就能正确统计实际的重复元素数量(案例中为3)。
内容的提问来源于stack exchange,提问作者Christian Jiga
相关产品推荐
相关产品推荐

