数据结构-单调栈

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


import java.util.Stack;

public class MonotonousStack {
    public static void main(String[] args) {
        int arr[] = {1,2,3,9,8,7,5,6,4};
        int res[][] = getNearLessNoRepeat(arr);
        for (int i = 0; i < res.length; i++) {
            System.out.println(res[i][0]+"  "+res[i][1]);
        }

        System.out.println("===================");
        int arr2[] = {1,6,3,9,5,8,7,5,2,6,4};
        int res2[][] = getNearLessRepeat(arr2);
        for (int i = 0; i < res2.length; i++) {
            System.out.println(res2[i][0]+"  "+res2[i][1]);
        }
    }

    // 数组不包含重复值
    public static int[][] getNearLessNoRepeat(int arr[]){
        int[][] res = new int[arr.length][2];
        // 栈存放的是数组arr的位置索引
        Stack<Integer> stack = new Stack<>();
        for (int i =0; i < arr.length; i++){
            while(!stack.isEmpty() && arr[stack.peek()] > arr[i]){
                // 当栈顶元素比arr[i]大时,就弹出栈
                int popIndex = stack.pop();
                int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();
                res[popIndex][0] = leftLessIndex;
                res[popIndex][1] = i;
            }
            stack.push(i);
        }

        // 当stack不为空时
        while(!stack.isEmpty()){
            int popIndex = stack.pop();
            int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();
            res[popIndex][0] = leftLessIndex;
            res[popIndex][1] = -1;
        }

        return res;
    }

    // 数组包含重复值
    public static int[][] getNearLessRepeat(int arr[]){
        int[][] res = new int[arr.length][2];
        Stack<Integer> stack = new Stack<>();
        for (int i =0; i < arr.length; i++){
            while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]){
                // 当栈顶元素>=arr[i]时,就弹出栈
                int popIndex = stack.pop();
                int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();
                res[popIndex][0] = leftLessIndex;
                res[popIndex][1] = i;
            }
            stack.push(i);
        }

        // 当stack不为空时
        while(!stack.isEmpty()){
            int popIndex = stack.pop();
            int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();
            res[popIndex][0] = leftLessIndex;
            res[popIndex][1] = -1;
        }

        for (int i = res.length-1; i >= 0; i--) {
             int index = res[i][1];
             if(index != -1 && arr[i] == arr[index]){
                 res[i][1] = res[index][1];
             }
        }

        return res;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值