文章目錄
1、逛街看樓
題目描述:
輸入第一行將包含一個數字n,代表樓的棟數,接下來的一行將包含n個數字wi(1<=i<=n)代表每棟樓的高度。
輸出一行,包含空格分割的n個數字vi,分別代表在第i棟樓時能看到的樓的數量(矮的樓會被高的樓擋住)
解題思路:
使用單調棧,先從左往右遍歷樓高數組,計算向左看能看到的樓層數目;再從右往左遍歷樓高數組,計算向右看能看到的樓層數目;最後每棟樓的位置上加1,代表自己所在樓也計算
輸入:6
5 3 8 3 2 5
輸出:3 3 5 4 4 4
import java.util.Scanner;
import java.util.Stack;
public class DandiaoZhan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] height = new int[n];
for (int i = 0; i < n; i++) {
height[i] = sc.nextInt();
}
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
res[i] +=stack.size();
while (!stack.empty() && height[i] > stack.peek())
stack.pop();
stack.push(height[i]);
}
stack.clear();
for (int i = n-1; i >= 0; i--) {
res[i] += stack.size();
while (!stack.empty() && height[i] > stack.peek())
stack.pop();
stack.push(height[i]);
}
for (int i = 0; i < n; i++) {
if (i != n-1)
System.out.printf("%d ", res[i]+1);
else
System.out.printf("%d", res[i]+1);
}
}
}