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

填充温度频率数组遇多频次数据中断问题求助

Fixing finalTemps Array Filling With 0s After a Temperature With Frequency >1

Your problem boils down to a key misstep: you’re using the raw temp array (which has duplicate entries for temperatures with frequency >1) to match against your continuous temperature range, instead of leaning on the HashMap you already built that holds exact frequency counts.

Why Your Current Code Fails

Let’s walk through the issue with your 14°C example:

  • When your loop reaches the index for 14°C, it matches temp[j] (which is 14), sets finalTemps[i] to 2, and increments j.
  • Now temp[j] is still 14 (since your raw temp array has two entries for 14), but the next tempGaps[i] is 15. These don’t match, so you set finalTemps[i] to 0 and keep incrementing j.
  • Eventually, j will run past the end of the temp array, and every subsequent tempGaps[i] will fail to match, leaving all remaining finalTemps values as 0.

The Fix: Use Your HashMap Directly

Since you already have a HashMap that maps each temperature to its frequency, you don’t need to touch the raw temp array at all. Here’s the corrected fillGaps method:

public void fillGaps() {
    // Critical fix: The number of continuous temps is (max - min + 1), not just difference
    int totalTemps = difference + 1;
    tempGaps = new int[totalTemps];
    finalTemps = new int[totalTemps];
    
    int minTemp = temp[0]; // Assuming temp is sorted, or you have a precomputed min temp
    for (int i = 0; i < totalTemps; i++) {
        int currentTemp = minTemp + i;
        tempGaps[i] = currentTemp;
        // Use getOrDefault to safely get frequency, defaulting to 0 if temp isn't present
        finalTemps[i] = map.getOrDefault(currentTemp, 0);
    }
}

Key Improvements

  • Ditched the j pointer and temp array dependency: Your HashMap is the single source of truth for frequencies—no need to iterate through raw data that has duplicates.
  • Fixed array length: Your original difference is maxTemp - minTemp, so the number of continuous temperatures is difference + 1 (e.g., 7 to 21 is 15 values, 21-7=14, 14+1=15). This prevents missing the highest temperature.
  • Simplified frequency lookup: HashMap.getOrDefault() handles both existing and missing temperatures in one line, no conditional checks needed.

Expected Result

With this fix, your finalTemps array will populate correctly:

  • For 14°C, it pulls the value 2 directly from the map
  • Subsequent temperatures like 15, 16, 18 will get their correct frequencies instead of 0
  • Missing temperatures (like 8, 11) will still show 0 as expected

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:52:54