A next greater element LeetCode 496. I (Next Greater Element I) 35

496. Under a greater element of the I
496. In the Next Element Greater the I

Title Description
Given two arrays nums1 no duplicate elements and nums2, wherein nums1 is a subset of nums2. Nums1 found under each element in a nums2 is larger than the value.

The next higher element numbers refer nums1 x x x corresponds to the first element is larger than the right position in the nums2. If not, the position output corresponding to -1.

Day algorithm 2019/6/7 Day 35 LeetCode 496. The Greater the Next Element the I

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [1,3, -1]
Explanation:
For num1 in figure 4, you are not in the second array to find the next larger number, and therefore the output 1.
For num1 in figures 1, the next higher number in a second array number 1 on the right is three.
For num1 in the number 2, the second array is no next larger number, and therefore the output 1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3, -1]
Explanation:
For num1 in the number 2, the second array to the next higher number 3.
For num1 in figures 4, the second array is no next larger number, and therefore the output 1.

note:

  1. nums1 and nums2 all elements are unique.
  2. nums1 and nums2 array size is not more than 1,000.

Java implementation

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer,Integer> map = new HashMap<>();
        Stack<Integer> stack = new Stack<>();
        for (int num:nums2) {
            while (!stack.isEmpty()&&num>stack.peek()){
                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;
    }
}

Similar topics

Reference material

Guess you like

Origin www.cnblogs.com/hglibin/p/10987847.html