算法训练营第五十八天|739. 每日温度、496.下一个更大元素 I

32 阅读1分钟

739. 每日温度

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Stack<Integer> monoStack = new Stack<>();
        int[] res = new int[temperatures.length];
        for(int i = 0; i < temperatures.length; i++){
            while(!monoStack.isEmpty() && temperatures[monoStack.peek()] < temperatures[i]){
                int idx = monoStack.pop();
                res[idx] = i - idx;
            }
            monoStack.add(i);
        }
        
        return res;
    }
}

496. 下一个更大元素 I

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Stack<Integer> monoStack = new Stack<>();
        Map<Integer, Integer> map = new HashMap<>(); // nums1中元素, nums2中下一个更大元素
        for(int i = 0; i < nums2.length; i++){
            while(!monoStack.isEmpty() && nums2[monoStack.peek()] < nums2[i]){
                map.put(nums2[monoStack.pop()], nums2[i]);
            }
            monoStack.push(i);
        }
        int[] res = new int[nums1.length];
        for(int i = 0; i < nums1.length; i++){
            res[i] = map.getOrDefault(nums1[i], -1);
        }
        return res;
    }
}