class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
// 存储数字 x 和下一个更大元素的映射关系
Map<Integer, Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for (int num : nums2) {
while (!stack.isEmpty() && stack.peek() < num) {
map.put(stack.pop(), num);
}
stack.push(num);
}
for (int i = 0; i < nums1.length; i++)
nums1[i] = map.getOrDefault(nums1[i], -1);
return nums1;
}
}
思路二:for循环从后往前遍历,元素倒序入栈,正序出栈
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
// 存储数字 x 和下一个更大元素的映射关系
Map<Integer, Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for (int i = nums2.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= nums2[i]) {
stack.pop();
}
if (!stack.isEmpty()) {
map.put(stack.peek(), nums2[i]);
}
stack.push(nums2[i]);
}
for (int i = 0; i < nums1.length; i++) {
nums1[i] = map.getOrDefault(nums1[i], -1);
}
return nums1;
}
}
leetcode-496-下一个更大元素I
最新推荐文章于 2024-07-21 15:36:00 发布