LeetCode No496.下一个更大元素 I
发布日期:2021-05-07 23:15:36 浏览次数:20 分类:原创文章

本文共 882 字,大约阅读时间需要 2 分钟。

题目描述

在这里插入图片描述

解法:单调栈

在这里插入图片描述

class Solution {       public int[] nextGreaterElement(int[] nums1, int[] nums2) {           int[] res = new int[nums1.length]; //需要返回的结果数组        Arrays.fill(res,-1);   //默认填充-1        HashMap<Integer,Integer> map = new HashMap<>(); //nums1中的值的对应下标        for (int i = 0; i < nums1.length; i++) {               map.put(nums1[i],i);        }        Stack<Integer> stack = new Stack<>(); //单调栈        for (int num : nums2) {               while(!stack.isEmpty() && stack.peek() < num){                   int pop = stack.pop();  //要移除的值                //判断这个值是不是在nums1中                Integer i = map.get(pop);                if(i != null){                       //不为空,表示在map的key中,也就说明在nums1中                    //更新res数组                    res[i] = num;   // 比pop大的元素就是这个当前访问的num                }            }            stack.push(num);        }        return res;    }}
上一篇:LeetCode No503.下一个更大元素 II
下一篇:LeetCode No402.移掉K位数字

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月05日 05时38分47秒