上善若水 大盈若冲
LeetCode link
solution
12345678910111213141516171819
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { int n1 = nums1.length; int[] result = new int[n1]; Map<Integer, Integer> map = new HashMap<>(); Stack<Integer> stack = new Stack<>(); for (int i = 0; i < nums2.length; i++) { while (!stack.isEmpty() && stack.peek() < nums2[i]) { int top = stack.pop(); map.put(top, nums2[i]); } stack.push(nums2[i]); } for (int i = 0; i < n1; i++) { result[i] = map.getOrDefault(nums1[i], -1); } return result; }}