常见笔试题

文章目录

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);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章