代码随想录算法训练营第五十一天|LeetCode503,42

目录

LeetCode 503.下一个更大元素II

LeetCode 42.接雨水


LeetCode 503.下一个更大元素II

文章讲解:代码随想录

力扣题目:LeetCode 503.下一个更大元素II

 代码随想录算法训练营第五十一天|LeetCode503,42_第1张图片

 代码如下(Java):

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        
        if(nums == null || nums.length <= 1)    return new int[]{-1};

        int size = nums.length;
        int[] result = new int[size];
        Arrays.fill(result, -1);
        Stack st = new Stack<>();

        for(int i = 0; i < 2 * size; i++){
            while(!st.empty() && nums[i % size] > nums[st.peek()]){
                result[st.peek()] = nums[i % size];
                st.pop();
            }
            st.push(i % size);
        }    

        return result;
    }
}

 

LeetCode 42.接雨水

文章讲解:代码随想录

力扣题目:LeetCode 42.接雨水

代码随想录算法训练营第五十一天|LeetCode503,42_第2张图片 

 代码如下(java):

class Solution {
    public int trap(int[] height) {

        int sum = 0;

        for(int i = 0; i < height.length; i++){
            if(i == 0 || i == height.length - 1)    continue;

            int rHeight = height[i];
            int lHeight = height[i];

            for(int r = i + 1; r < height.length; r++){
                if(height[r] > rHeight) rHeight = height[r];
            }

            for(int l = i-1; l >= 0; l--){
                if(height[l] > lHeight) lHeight = height[l];
            }

            int h = Math.min(lHeight, rHeight) - height[i];

            if(h > 0)   sum += i;
        }

        return sum;
    }
}

你可能感兴趣的:(算法)