代码随想录二刷day59

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣503. 下一个更大元素 II
  • 二、力扣42. 接雨水


前言


一、力扣503. 下一个更大元素 II

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int[] res = new int[nums.length];
        Arrays.fill(res, -1);
        int[] arr = new int[nums.length*2];
        for(int i = 0; i < arr.length; i ++){
            arr[i] = i%nums.length;
        }
        Deque<Integer> deq = new ArrayDeque<>();
        deq.offerLast(0);
        for(int i = 1; i < arr.length; i ++){
            if(nums[arr[i]] <= nums[deq.peekLast()]){
                deq.offerLast(arr[i]);
            }else{
                while(!deq.isEmpty() && nums[arr[i]] > nums[deq.peekLast()]){
                    int index = deq.pollLast();
                    res[index] = nums[arr[i]];
                }
                deq.offerLast(arr[i]);
            }
        }
        return res;
    }
}

二、力扣42. 接雨水

class Solution {
    public int trap(int[] height) {
        int count = 0;
        Deque<Integer> deq = new ArrayDeque<>();
        deq.offerLast(0);
        for(int i = 1; i < height.length; i ++){
            if(height[i] < height[deq.peekLast()]){
                deq.offerLast(i);
            }else if(height[i] == height[deq.peekLast()]){
                deq.pollLast();
                deq.offerLast(i);
            }else{
                while(!deq.isEmpty() && height[i] > height[deq.peekLast()]){
                    int mid = deq.pollLast();
                    if(deq.isEmpty()){
                        break;
                    }
                    int left = height[deq.peekLast()];
                    int right = height[i];
                    int len = Math.min(left, right) - height[mid];
                    int width = i - deq.peekLast() - 1;
                    count += len * width;
                }
                deq.offerLast(i);
            }
        }
        return count;
    }
}

你可能感兴趣的:(算法,java,数据结构,leetcode)