Next Greater Element I

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

思路:这个题目很好,是单调栈的经典题型;找右边第一个比 num[i]要大的数,那么从右边来的比当前num 小的数,就没必要存,stack里面只存比stack peek 大的数,来的数比peak大,那么踢掉peek,同时踢掉的时候记录peek的next great elment就是踢掉的那个值,整个stack就是一个单调递减栈。这题精妙的地方在于,用hashmap去存右边第一个比他大的数的mapping,也就是存右边第一个踢到这个数的num;如果没有人踢他,代表右边没有人比他大;getOrDefault(nums1[i], -1);

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int[] res = new int[n];
        Arrays.fill(res, -1);
        HashMap<Integer, Integer> hashmap = new HashMap<>();
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < nums2.length; i++) {
            if(stack.isEmpty()) {
                stack.push(i);
            } else {
                while(!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) {
                    int index = stack.pop();
                    hashmap.put(nums2[index], nums2[i]);
                }
                stack.push(i);
            }
        }
        for(int i = 0; i < n; i++) {
            if(hashmap.containsKey(nums1[i])) {
                res[i] = hashmap.get(nums1[i]);
            }
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值