首页 > 其他分享 >代码随想录训练营第五十八章|单调栈

代码随想录训练营第五十八章|单调栈

时间:2022-12-10 16:46:28浏览次数:70  
标签:int res 训练营 随想录 第五十八章 length new nums1 单调

今天是训练营第五十八天,是最后一天单调栈的开始

 

 

739. 每日温度 

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] res = new int[n];
        int[] stack = new int[n];
        int top = -1;
        for(int i = n-1; i>=0; i--){
            while(top >=0 &&temperatures[stack[top]]<=temperatures[i]){
                top--;
            }
            res[i] = top == -1 ? 0: stack[top] -i;
            stack[++top] = i;
        }
        return res;
    }
    
}

单调栈的模版题

496.下一个更大元素 I 

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Stack<Integer> temp = new Stack<>();
        int[] res = new int[nums1.length];
        Arrays.fill(res,-1);
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0 ; i< nums1.length ; i++){
            hashMap.put(nums1[i],i);
        }
        temp.add(0);
        for (int i = 1; i < nums2.length; i++) {
            if (nums2[i] <= nums2[temp.peek()]) {
                temp.add(i);
            } else {
                while (!temp.isEmpty() && nums2[temp.peek()] < nums2[i]) {
                    if (hashMap.containsKey(nums2[temp.peek()])){
                        Integer index = hashMap.get(nums2[temp.peek()]);
                        res[index] = nums2[i];
                    }
                    temp.pop();
                }
                temp.add(i);
            }
        }

        return res;
    }
}

题意比较难理解,要转化为单调栈问题

 

明天继续单调栈

标签:int,res,训练营,随想录,第五十八章,length,new,nums1,单调
From: https://www.cnblogs.com/catSoda/p/16971819.html

相关文章