代码模板 - 单调栈

代码模板 - 单调栈

// code 
// 给定数组arr, 返回数组中每个元素左右边比其小的第一个值的位置值,返回二维数组
// [1, 2, 0, 9, 8]
//  0  1  2  3  4
// [[-1, 2],[0, 2],[-1, -1],[2, 4],[2, -1]]

// 数组中无重复
int[][] getNearLessNoRepeat(int[] arr) {
    if (arr == null || arr.length == 0) {
        return null;
    }
    int N = arr.length;
    int[][] ans = new int[N][2];
    Stack<Integer> stack = new Stack<>();
    for (int i = 0; i < N; i++) {
        if (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
            int cur = stack.pop();
            ans[cur][0] = stack.isEmpty() ? -1 : stack.peek();
            ans[cur][1] = i;
        }
        stack.push(i);
    }
    while (!stack.isEmpty()) {
        int cur = stack.pop();
        ans[cur][0] = stack.isEmpty() ? -1 : stack.peek();
        ans[cur][1] = -1;
    }
    return ans;
}

// 数组有重复值
int[][] getNearLessRepeat(int[] arr) {
    if (arr == null || arr.length == 0) {
        return null;
    }
    int N = arr.length;
    int[][] ans = new int[N][2];
    Stack<List<Integer>> stack = new Stack<>();
    for (int i = 0; i < N; i++) {
        if (!stack.isEmpty() && arr[stack.peek().get(0)] > arr[i]) {
            List<Integer> cur = stack.pop();
            for (int index : cur) {
                // 注意indexList取值顺序
                ans[index][0] = stack.isEmpty() ? -1 : stack.peek().get(stack.peek().size() - 1);
                ans[index][1] = i;
            }
        }
        if (!stack.isEmpty() && arr[stack.peek().get(0)] == arr[i]) {
            stack.peek().add(i);
        } else {
            List<Integer> list = new ArrayList<>();
            list.add(i);
            stack.push(list);
        }
    }
    while (!stack.isEmpty()) {
        List<Integer> cur = stack.pop();
        for (int index : cur) {
            ans[index][0] = stack.isEmpty() ? -1 : stack.peek().get(stack.peek().size() - 1);
            ans[index][1] = -1;
        }
    }
    return ans;
}

posted @ 2023-04-23 10:59  我见青山应如是  阅读(12)  评论(0编辑  收藏  举报