classSolution{ publicint[] nextGreaterElement(int[] nums1, int[] nums2) { Deque<Integer> stack = new LinkedList<>(); // 记录nums2中的元素x的下一个更大元素 Map<Integer,Integer> map = new HashMap<>(); int[] res = newint[nums1.length];
// 先遍历nums2,找到每个元素的下一个更大元素 for (int i = 0; i < nums2.length; i++) { while (!stack.isEmpty() && nums2[i]>nums2[stack.peek()]) { int top = stack.pop(); map.put(nums2[top],nums2[i]); } stack.push(i); }
for (int i = 0; i < nums1.length; i++) { int n = map.getOrDefault(nums1[i],-1); // 不存在则置-1 res[i] = n; } return res; } }
classSolution{ publicint[] nextGreaterElements(int[] nums) { Deque<Integer> stack = new LinkedList<>(); int n = nums.length; int res[] = newint[n]; Arrays.fill(res,-1); for (int i = 0; i < 2*n; i++) { // 设为2*n即可 int j = i%n; while (!stack.isEmpty()&&nums[j]> nums[stack.peek()]){ int top = stack.pop(); res[top] = nums[j]; } stack.push(j); } return res; } }