1.视野总和

739.每日温度

package monotoneStack;

import org.junit.Test;

import java.util.Stack;

/**
 * @description:
 * @author: weitao_wang
 * @date: 2023/4/20 10:04
 */
public class monStackPrac {
    private int[] arr = new int[]{3,1,5,7,3,2,4,6,1,9,3};
    private Stack<Integer> st = new Stack<>();

    /**
     * 单调递增栈,栈底到栈顶 单调递增
     *     用于寻找两侧第一个比它小的元素
     *     左侧()  右侧(从后往前遍历)
     */
    @Test
    public void test1() {
        //
    }

    /**
     * 单调递减栈,栈底 --> 栈顶  单调递减
     *       用于寻找两侧第一个比它大的元素
     *       左侧()   右侧(从后往前遍历)
     */
    @Test
    public void test2() {
        st.clear();
        for(int i = 0; i < arr.length; i++) {
            System.out.printf("%3d ", arr[i]);
            
            
            while(!st.empty() && st.peek() < arr[i]) st.pop();
            System.out.printf("%3d ", st.empty() ? -1 : st.peek());
            st.push(arr[i]);
            
            
            System.out.println();
        }
    }
}

496. 下一个更大元素 I

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] ans = new int[nums1.length];
        Stack<Integer> st = new Stack<>(); //单调栈
        Map<Integer, Integer> numMap = new HashMap<>();
        for(int i = nums2.length - 1; i >= 0; i--) {
            while(!st.empty() && nums2[i] > st.peek()) {
                st.pop();
            }
            if(!st.empty())numMap.put(nums2[i], st.peek());
            st.push(nums2[i]);
        }
        for(int i = 0 ; i < nums1.length; i++){
            ans[i] = numMap.getOrDefault(nums1[i], -1);
        }
        return ans;
    }
}

好的博客

单调栈分析
单调栈:快速找到

Posted on 2023-04-10 17:27  Nonur  阅读(8)  评论(0编辑  收藏  举报