算法训练第五十九天 | LeetCode 503、42

LeetCode 503下一个更大元素II

题目简析:

给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素 ,循环数组中去找。

思路分析:

本题难点在于如何模拟循环数组来检索

我们只需要处理遍历的长度为2*len,然后用当前下标去%len,其余的内容就跟每日温度一样啦

    //本题难点就是如何模拟循环数组
    public int[] nextGreaterElements(int[] nums) {
        int len = nums.length;
        //因为找不到就是-1,那么我们就得先将数组初始化为-1
        int []res = new int[len];
        Arrays.fill(res,-1);
        if (len == 0) return res;
        //单调栈的做法就是存下标然后通过下标去原来数组找值
        //通过两者比对来确定结果
        Stack<Integer> stack = new Stack<>();
        //注意数组中结果的是值
        for (int i = 0; i < len*2; i++) {
            // 模拟遍历两边nums,注意一下都是用i % len来操作
            while (!stack.isEmpty() && nums[i % len] > nums[stack.peek()]) {
                res[stack.peek()] = nums[i % len];
                stack.pop();
            }
            stack.push(i % len);
        }
        return res;
    }

LeetCode 42接雨水

题目简析:

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

思路分析:

本题一刷就了解的不太到位了,后面复习再来

    public int trap(int[] height){
        int size = height.length;

        if (size <= 2) return 0;
        
        // in the stack, we push the index of array
        // using height[] to access the real height
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(0);

        int sum = 0;
        for (int index = 1; index < size; index++){
            int stackTop = stack.peek();
            if (height[index] < height[stackTop]){
                stack.push(index);
            }else if (height[index] == height[stackTop]){
                // 因为相等的相邻墙,左边一个是不可能存放雨水的,所以pop左边的index, push当前的index
                stack.pop();
                stack.push(index);
            }else{
                //pop up all lower value
                int heightAtIdx = height[index];
                while (!stack.isEmpty() && (heightAtIdx > height[stackTop])){
                    int mid = stack.pop();
                    
                    if (!stack.isEmpty()){
                        int left = stack.peek();

                        int h = Math.min(height[left], height[index]) - height[mid];
                        int w = index - left - 1;
                        int hold = h * w;
                        if (hold > 0) sum += hold;
                        stackTop = stack.peek();
                    }
                }
                stack.push(index);
            }
        }
        
        return sum;
    }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值