# 0496. Next Greater Element I ###### tags: `Leetcode` `Easy` `Stack` `FaceBook` Link: https://leetcode.com/problems/next-greater-element-i/ ## 思路 O(N) O(N) 先用map存,nums2里面的每个元素和它next greater element的对应 然后再用回圈遍历nums1,找到答案 ## Code ```java= class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Stack<Integer> stack = new Stack<>(); Map<Integer, Integer> map = new HashMap<>(); for(int i = 0;i < nums2.length;i++){ while(!stack.isEmpty() && nums2[stack.peek()]<nums2[i]){ map.put(nums2[stack.pop()], nums2[i]); } stack.push(i); } int[] res = new int[nums1.length]; for(int i = 0;i < nums1.length;i++){ res[i] = map.getOrDefault(nums1[i], -1); } return res; } } ```