栈-leetcode 496. Next Greater Element I

来源:互联网 发布:上海巨人网络校园招聘 编辑:程序博客网 时间:2024/06/08 00:57

原题链接:Next Greater Element I


题解:

public class Solution {    public int[] nextGreaterElement(int[] findNums, int[] nums) {        /*            Time Complexity:O(N)            Space Complexity:O(N)        */                if(nums==null || nums.length==0)return new int[]{};        HashMap<Integer,Integer>map=new HashMap<>();        ArrayDeque<Integer>sta=new ArrayDeque<>();        for(int num:nums){            while(!sta.isEmpty() && sta.peek()<num){                map.put(sta.pop(),num);            }            sta.push(num);        }        int[] res=new int[findNums.length];        for(int i=0;i<findNums.length;i++){            res[i]=map.getOrDefault(findNums[i],-1);        }        return res;            }}