单调栈 ---

下一个更大元素

Nums1中的数在nums2中找,用hashmap来存放nums2以及下一个更大元素

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer,Integer> map=new HashMap<>();//用于存放在nums2下一个更大元素
        Deque<Integer> s=new LinkedList<>();//单调栈
        for(int i=nums2.length-1;i>=0;i--){//倒着遍历
            while(!s.isEmpty()&&nums2[i]>=s.peek()){//弹出小的
                s.pop();
            }
            int x=s.isEmpty() ?-1:s.peek();
            s.push(nums2[i]);
            map.put(nums2[i],x);
        }
         int[] res=new int[nums1.length];
         for(int i=0;i<nums1.length;i++){
            int y=map.get(nums1[i]);
            res[i]=y;
         }
         return res;
    }
}

每日温度(存储的是索引 存储的是索引 索引

因为温度会重复,所以不能用map

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Deque<Integer> s=new LinkedList<>();
        int[] res=new int[temperatures.length];
        for(int i=temperatures.length-1;i>=0;i--){
            while(!s.isEmpty()&&temperatures[s.peek()]<=temperatures[i]){//弹出小的
                s.pop();
            }
            int x= s.isEmpty()? 0:(s.peek()-i);
            res[i]=x;
            s.push(i);
            
        }
        return res;
    }
}

环形数组(取余来构建循环数组,取余来模拟数组长度翻倍

   

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int len=nums.length;
        int[] res=new int[len];
        Deque<Integer> s=new LinkedList<>();
        for(int i=2*len-1;i>=0;i--){//数组翻倍循环数组
            while (!s.isEmpty() && s.peek() <= nums[i % len]) {
                s.pop();
            }
            res[i%len]= s.isEmpty()? -1:s.peek();
            s.push(nums[i%len]);
        }
        return res;
    }
}

i%len,2*len-1关键点

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值