填充温度频率数组遇多频次数据中断问题求助
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), setsfinalTemps[i]to 2, and incrementsj. - Now
temp[j]is still 14 (since your rawtemparray has two entries for 14), but the nexttempGaps[i]is 15. These don’t match, so you setfinalTemps[i]to 0 and keep incrementingj. - Eventually,
jwill run past the end of thetemparray, and every subsequenttempGaps[i]will fail to match, leaving all remainingfinalTempsvalues 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
jpointer andtemparray dependency: YourHashMapis the single source of truth for frequencies—no need to iterate through raw data that has duplicates. - Fixed array length: Your original
differenceismaxTemp - minTemp, so the number of continuous temperatures isdifference + 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
相关产品推荐
相关产品推荐

