[Leetcode - 496] at a greater element -Easy

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.

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:

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

 

【original】

Ideas: Consider each element nums1 num2 in position, behind slice selection position, to find a value greater than the first element out of the loop

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        dic = {}
        stack = []
        for i, j in enumerate(nums2):
            dic[j] = -1
            for k in nums2[i+1:]:
                if k>j:
                    dic[j] = k
                    break
        for p in nums1:
            if p in nums2:
                stack.append(dic[p])
            else:
                stack.append(-1)
        return stack
original

【upgrade】

Ideas: maintaining a monotonous stack, when traversing nums2, if the stack is not empty, and a new element is greater than one element, the new element as existing elements of the next higher stack all the elements, i.e., determining a new element is greater than the last element of the stack, the result is positive then the stack, continuous loop until empty, every time you add a new value dictionary. If greater than the last element in the stack, the stack. Nums1 final result corresponding to the value taken from the dictionary, if there is no return -1

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        dic = {}
        stack = []
        for i in nums2:
            while stack and stack[-1]<i:
                dic[stack.pop()] = i
            stack.append(i)
        return [dic.get(i,-1) for i in nums1]
Upgrade

 

Guess you like

Origin www.cnblogs.com/akassy/p/12632134.html