刷题12.8

1 每日温度

题目

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

代码

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int len=temperatures.length;
        int[] res=new int[len];
        Deque<Integer> stack=new LinkedList<>();
        stack.push(0);
        for(int i=1;i<len;i++){
            if(temperatures[i]<=temperatures[stack.peek()])
                stack.push(i);
            else{
                while(!stack.isEmpty() && temperatures[i]>temperatures[stack.peek()]){
                    res[stack.peek()]=i-stack.peek();
                    stack.pop();
                }
                stack.push(i);
            }
        }
        return res;
    }
}

总结

细节:栈中的元素的 下标(这也是为啥开始栈中加入0,0是下标)

2 下一个更大的元素I

题目

nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。
给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。
对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。
返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。

代码

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

总结

注意题目的提示:nums1 中的所有整数同样出现在 nums2 中。
和上一题的不同之处就是,res如何记录结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值