第一章 栈和队列(单调栈结构)

题目描述
给定一个可能含有重复值的数组 arr,找到每一个 i 位置左边和右边离 i 位置最近且值比 arr[i] 小的位置。返回所有位置相应的信息。

输入描述:
第一行输入一个数字 n,表示数组 arr 的长度。
以下一行输入 n 个数字,表示数组的值

输出描述:
输出n行,每行两个数字 L 和 R,如果不存在,则值为 -1,下标从 0 开始。

示例:

输入
7
3 4 1 5 6 2 7

输出
-1 2
0 2
-1 -1
2 5
3 5
2 -1
5 -1

    public static void main(String[] args) {
        Integer[] arr = {3, 4, 1, 5, 6, 2, 7};
        int[][] ints1 = noRepeat(arr);
        for (int[] ints : ints1) {
            System.out.println(String.format("(%s,%s)", ints[0], ints[1]));
        }
    }

    static int[][] noRepeat(Integer[] arr) {
        // 存放数组下标值
        Stack<Integer> indexStack = new Stack<Integer>();
        // 存放返回结果
        int[][] res = new int[arr.length][2];
        for (int i = 0; i < arr.length; i++) {
            //
            while (!indexStack.isEmpty() && arr[indexStack.peek()] > arr[i]) {
                Integer cur = indexStack.pop();
                int leftLessIndex = indexStack.isEmpty() ? -1 : indexStack.peek();
                res[cur][0] = leftLessIndex;
                res[cur][1] = i;
            }
            indexStack.add(i);
        }
        while (!indexStack.isEmpty()) {
            Integer cur = indexStack.pop();
            int leftLessIndex = indexStack.isEmpty() ? -1 : indexStack.peek();
            res[cur][0] = leftLessIndex;
            res[cur][1] = -1;
        }
        return res;
    }
(-1,2)
(0,2)
(-1,-1)
(2,5)
(3,5)
(2,-1)
(5,-1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值