《LeetCode力扣练习》代码随想录——单调栈(下一个更大元素 I—Java)
刷题思路来源于 代码随想录
496. 下一个更大元素 I
-
单调栈
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { if (nums1.length == 0) { return new int[0]; } int[] result = new int[nums1.length]; Arrays.fill(result, -1); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums1.length; i++) { map.put(nums1[i], i); } Deque<Integer> stack = new ArrayDeque<>(); stack.push(0); for (int i = 1; i < nums2.length; i++) { if (nums2[i] <= nums2[stack.peek()]) { stack.push(i); } else { while (!stack.isEmpty() && nums2[i] > nums2[stack.peek()]) { int index = nums2[stack.peek()]; if (map.containsKey(index)) { result[map.get(index)] = nums2[i]; } stack.pop(); } stack.push(i); } } return result; } }