每段建筑物的平均高度
难度:
标签:
题目描述
代码结果
运行时间: 335 ms, 内存: 86.5 MB
/*
* Problem: Given an array of building heights, find the average height of each building block.
* Solution: Use Java Streams to calculate the sum and count, then find the average.
*/
import java.util.Arrays;
public class AverageBuildingHeightStream {
public static double findAverageHeight(int[] heights) {
return Arrays.stream(heights).average().orElse(0);
}
}
解释
方法:
The solution uses a line sweep algorithm combined with differential counting. For each building, start and end positions are marked in a 'diff' dictionary where heights are added at the start and subtracted at the end. Another 'cnts' dictionary tracks how many buildings start or end at each point. By iterating over the sorted keys of these dictionaries, we compute the current total height and count of buildings at each position. This allows us to determine the average height for any segment where it remains constant. The result is appended to the list if the average height changes from the previous segment or a new segment starts.
时间复杂度:
O(k log k)
空间复杂度:
O(k)
代码细节讲解
🦆
如何保证在使用`diff`和`cnts`字典时,所有建筑的开始和结束位置都被正确处理,没有遗漏或重复?
▷🦆
在计算平均高度时,如果`cnt`为零会怎样处理?即没有建筑物覆盖的区间应如何表示?
▷🦆
当两个或多个建筑物在某些点重叠时,如何确保`diff`字典和`cnts`字典能正确反映所有建筑的总高度和数量?
▷🦆
在最后一个位置处理结束后,如何确保最后一个区间被正确添加到结果列表`ans`中,尤其是当最后一个区间的平均高度与之前的不同时?
▷