Tall Building高楼大厦
Description
At the weekend, Xiao Q and his friends came to the big city for shopping. There are many tall buildings.There are n tall buildings in a row, whose height is indicated by arr. Xiao Q has walked from the first building to the last one. Xiao Q has never seen so many buildings, so he wants to know how many buildings can he see at the location of each building? (When the height of the front building is greater than or equal to the back building, the back building will be blocked)
Input:[5,3,8,3,2,5]
Output:[3,3,5,4,4,4]
Explanation:
When Xiao Q is at position 0, he can see 3 tall buildings at positions 0, 1, and 2.
When Xiao Q is at position 1, he can see 3 tall buildings at positions 0, 1, and 2.
When Xiao Q is at position 2, he can see the building at position 0, 1 forward, and the building at position 3, 5 backward, plus the third building, a total of 5 buildings can be seen.
When Xiao Q is at position 3, he can see 4 tall buildings in positions 2, 3, 4, and 5.
When Xiao Q is at position 4, he can see 4 tall buildings in positions 2, 3, 4, and 5.
When Xiao Q is at position 5, he can see 4 tall buildings in positions 2, 3, 4, and 5.
public class Solution {
/**
* @param arr: the height of all buildings
* @return: how many buildings can he see at the location of each building
*/
public int[] tallBuilding(int[] arr) {
// Write your code here.
/* if(arr == null || arr.length == 0){
return null ;
}
int[] result = new int[arr.length] ;
for(int i = 0 ; i < arr.length ; i++){
int count = 0 , temp = 0 ;
int max1 = Integer.MIN_VALUE ;
int max2 = Integer.MIN_VALUE ;
for(int j = i +1 ; j < arr.length ; j++ ){
if(arr[j] > max1 ){
count++ ;
max1 = arr[j] ;
}
}
for(int k = i -1 ; k >= 0 ; k--){
if(arr[k] > max2 ){
temp++ ;
max2 = arr[k] ;
}
}
if(i == 0){
result[i] = count + 1 ;
}else{
result[i] = count + temp +1 ;
}
}
return result ;*/
if(arr == null || arr.length == 0){
return null ;
}
int[] result = new int[arr.length] ;
Arrays.fill(result,1) ;
Deque<Integer> stack = new ArrayDeque<Integer>() ;
for(int i = 0 ; i < arr.length ; i++){
result[i] += stack.size() ;
while(!stack.isEmpty() && stack.peek() <= arr[i]){
stack.poll() ;
}
stack.push(arr[i]) ;
}
stack.clear() ;
for(int i = arr.length-1 ; i >= 0 ; i--){
result[i] += stack.size() ;
while(!stack.isEmpty() && stack.peek() <= arr[i]){
stack.poll() ;
}
stack.push(arr[i]) ;
}
return result ;
}
}
这篇博客介绍了如何计算一个人在高楼大厦间行走时能看到的建筑物数量。给定一个表示各栋建筑高度的数组,算法需要确定在每个位置上可以看到多少栋建筑。当前方建筑高于或等于后方建筑时,后方建筑会被遮挡。提供的解决方案使用了双端队列实现,有效地找出每个位置的可视建筑数。
504

被折叠的 条评论
为什么被折叠?



