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 peek 大的数,那么就是单调递减栈。这题精妙的地方在于,用hashmap去存右边第一个比他大的数的mapping,也就是存右边第一个踢到这个数的num;如果没有人踢他,代表右边没有人比他大;getOrDefault(nums1[i], -1);

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        // 左右两边第一个比他大的数,用递减栈;
        // 用hashmap去存,右边第一个比他大的数;
        HashMap hashmap = new HashMap<>();
        Stack stack = new Stack();
        for(int i = 0; i < nums2.length; i++) {
            int num = nums2[i];
            while(!stack.isEmpty() && stack.peek() < num) {
                hashmap.put(stack.pop(), num);
            }
            stack.push(num);
        }
        
        int[] res = new int[nums1.length];
        for(int i = 0; i < nums1.length; i++) {
            res[i] = hashmap.getOrDefault(nums1[i], -1);
        }
        return res;
    }
}

 

你可能感兴趣的:(Stack)