You need to enable JavaScript to run this app. 如何统计整数数组中各数字的出现频率
优惠活动
大模型
产品
解决方案
定价
更多

如何统计整数数组中各数字的出现频率

现有代码的运行逻辑偏差点

  • 基础语法错误:int size = 7语句末尾缺失分号,直接触发编译失败
  • 内层循环条件书写错误:误将循环变量j的边界判断写为i<size-1,由于外层循环的i值固定递增,该判断会永久成立,直接触发内层死循环
  • 计数逻辑存在初始值缺失:匹配到相同元素时,仅累加后续匹配到的元素个数,未将当前遍历位置的元素本身计入统计值,最终结果会比实际出现次数少1
  • 无重复元素过滤机制:数组中重复出现的数字(如本例的3、6)会被多次遍历,输出冗余的重复统计内容
  • 遍历范围边界错误:内层循环仅遍历到size-1位置,会漏掉数组最后一个元素的匹配判断

适配原思路的修正代码

保留原代码“标记已统计元素、避免重复处理”的核心思路,修正所有逻辑bug后的可运行版本如下:

int size = 7;
int aux [] = {3,4,6,6,10,3,5};
for(int i = 0 ; i<size; i++) {
    // 跳过已经被标记为已统计的元素
    if(aux[i] == -1) {
        continue;
    }
    int currentNum = aux[i];
    int cont = 1; // 初始计数包含当前元素本身
    // 从当前元素的下一位开始遍历,减少无意义的重复比较
    for(int j = i+1; j < size; j++) {
        if(currentNum == aux[j]) {
            aux[j] = -1;
            cont++;
        } 
    }
    System.out.println("The number "+ currentNum + " appears "+ cont +" times");
}

该代码运行后输出结果为:

  • The number 3 appears 2 times
  • The number 4 appears 1 times
  • The number 6 appears 2 times
  • The number 10 appears 1 times
  • The number 5 appears 1 times

更通用的实现方案

如果需要不修改原数组、适配任意取值范围的整数数组,可以借助哈希表完成频率统计,代码如下:

int size = 7;
int aux [] = {3,4,6,6,10,3,5};
Map<Integer, Integer> frequencyMap = new HashMap<>();
for(int num : aux) {
    frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
for(Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
    System.out.println("The number "+ entry.getKey() + " appears "+ entry.getValue() +" times");
}

内容的提问来源于stack exchange,提问作者Juanetoh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.17 08:45:01