力扣503、42打卡第59天

503. 下一个更大元素 II

这里很巧妙的运用了一个技巧,那就是使用了双倍的长度,让这个数组长度乘以二,然后从表象上制造一种循环的错觉,代码如下:

    public int[] nextGreaterElements(int[] nums) {
        int[] re = new int[nums.length];
        Arrays.fill(re,-1);

        Stack<Integer> st = new Stack();
        int size = nums.length;
        st.push(0);
        for(int i=1;i<size*2;i++){
            while(!st.empty() && nums[i % size] > nums[st.peek()]) {
                re[st.peek()] = nums[i % size];//更新result
                st.pop();//弹出栈顶
            }
            st.push(i % size);
        }
        return re;
    }

42. 接雨水

这里用到单调栈的技巧请务必记牢,计算过程大致为,先将栈顶元素取出,然后将用当前元素和目前栈顶元素的最小值减去取出的元素为高,然后用栈顶元素的坐标减去当前元素的坐标为宽进行计算,代码如下:

    public int trap(int[] height) {
        Stack<Integer> st = new Stack();
        st.push(0);
        int re = 0;
        int w = 0;
        int h = 0;
        int tool;
        for(int i=0;i<height.length;i++){
            if(height[i]<=height[st.peek()])st.push(i);
            else{
                while(!st.isEmpty()&&height[i]>height[st.peek()]){
                    tool = st.pop();
                    if(!st.isEmpty()){
                        h = Math.min(height[st.peek()],height[i])-height[tool];
                        w = i-st.peek()-1;
                        re+=h*w;
                    }
                    
                }
                st.push(i);
            }
        }
        return re;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值