LeetCode 2015: Average Height of Buildings in Each Segment Solution
Master LeetCode problem 2015 (Average Height of Buildings in Each Segment), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2015. Average Height of Buildings in Each Segment
Problem Explanation
Explanation:
Given a list of buildings represented by their heights, the task is to find the average height of buildings in each segment. A segment is defined as a continuous subarray of the buildings.
To solve this problem, we can iterate through each segment, calculate the average height of the buildings in that segment, and store the result in a list.
Here is the step-by-step algorithm:
- Initialize an empty list to store the average heights of each segment.
- Iterate through each segment:
- Calculate the sum of heights in the current segment.
- Calculate the average height by dividing the sum by the number of buildings in the segment.
- Append the average height to the result list.
- Return the list of average heights.
Time complexity: O(N), where N is the number of buildings in the input list. Space complexity: O(1) excluding the space required for the output list. :
Solution Code
public List<Double> averageOfBuildings(int[] buildings) {
List<Double> averages = new ArrayList<>();
for (int i = 0; i < buildings.length; i++) {
double sum = 0;
int count = 0;
for (int j = i; j < buildings.length; j++) {
sum += buildings[j];
count++;
averages.add(sum / count);
}
}
return averages;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2015 (Average Height of Buildings in Each Segment)?
This page provides optimized solutions for LeetCode problem 2015 (Average Height of Buildings in Each Segment) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2015 (Average Height of Buildings in Each Segment)?
The time complexity for LeetCode 2015 (Average Height of Buildings in Each Segment) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2015 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2015 in Java, C++, or Python.