496. 下一个更大元素 I

  1. class Solution {
  2. public int[] nextGreaterElement(int[] nums1, int[] nums2) {
  3. if (nums1 == null || nums1.length == 0)
  4. return new int[0];
  5. Deque<Integer> stack = new LinkedList<>();
  6. Map<Integer, Integer> map = new HashMap<>();
  7. for (int i = 0; i < nums2.length; i++) {
  8. while (!stack.isEmpty() && nums2[i] > stack.peek()) {
  9. map.put(stack.pop(), nums2[i]);
  10. }
  11. stack.push(nums2[i]);
  12. }
  13. while (!stack.isEmpty()) {
  14. map.put(stack.pop(), -1);
  15. }
  16. int[] ans = new int[nums1.length];
  17. for (int i = 0; i < nums1.length; i++) {
  18. ans[i] = map.get(nums1[i]);
  19. }
  20. return ans;
  21. }
  22. }