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 ;
}
}