You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java HashMap统计数组中各数字出现的对数并输出指定格式结果

解决方法

核心实现逻辑:

  • 成对次数 = 数字出现次数做整数除法除以2,直接舍去余数
  • 仅保留成对次数大于0的数字参与输出
  • 按要求拼接输出字符串即可

修改后的完整代码如下:

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;

class Trail{
    static void countFreq(int arr[], int n)
    {
        Map<Integer, Integer> mp = new HashMap<>();
 
        // 统计每个数字出现频次
        for (int i = 0; i < n; i++)
        {
            if (mp.containsKey(arr[i]))
            {
                mp.put(arr[i], mp.get(arr[i]) + 1);
            }
            else
            {
                mp.put(arr[i], 1);
            }
        }
        // 存储符合要求的输出片段
        List<String> outputParts = new ArrayList<>();
        // 遍历计算成对次数
        for (Map.Entry<Integer, Integer> entry : mp.entrySet())
        { 
            int pairCount = entry.getValue() / 2;
            if(pairCount > 0) {
                // 处理单复数格式适配
                String pairStr = pairCount == 1 ? "pair" : "pairs";
                outputParts.add(pairCount + " " + pairStr + " of number " + entry.getKey());
            }
        }
        // 拼接所有片段输出
        System.out.println(String.join(", ", outputParts));
         
    }

    public static void main(String[] args) {
        int arr[] = {1,2,1,2,1,3,2,1};
        int n = arr.length;
        countFreq(arr, n);
    }
}

代码修改说明

  • 补全了必要的依赖包导入语句,避免编译报错
  • 新增outputParts列表存储符合输出要求的文本片段,不需要手动处理逗号分隔的边界问题
  • 对每个数字的频次做整数除法得到成对次数,自动过滤掉成对次数为0的条目
  • 适配了pair的单复数格式,和要求的输出完全匹配
  • 最终用String.join拼接所有片段,直接得到符合要求的输出结果

运行上述代码会直接输出期望结果:

2 pairs of number 1, 1 pair of number 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:36:03