栈与队列

下一个更大元素 I

2025-10-15  本文已影响0人  何以解君愁

下一个更大元素 I

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        //x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素
        int[] res = new int[nums1.length];
        Arrays.fill(res,-1);
        Deque<Integer> stack = new ArrayDeque<>();
        Map<Integer,Integer> map = new HashMap<>();

        for(int i = 0;i < nums2.length;i++){
            //先处理另一个栈,按单调栈处理法,保存到map,通过元素值与大于的元素值进行映射
            while(!stack.isEmpty()&&nums2[i] > nums2[stack.peek()]){
                int number = nums2[stack.pop()];
                map.put(number,nums2[i]);
            }
            stack.push(i);
        }

        for(int i = 0; i < nums1.length;i++){
            if(map.containsKey(nums1[i])){
                res[i] = map.get(nums1[i]);
            }
        }
        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读