LeetCodeEasy- [496. The next larger element I]

Given two arrays with no duplicate elements, nums1 and nums2, where nums1 is a subset of nums2. Find the next larger value of each element in nums1 in nums2.

The next larger element of the number x in nums1 refers to the first element to the right of x corresponding to the position in nums2 that is greater than x. If it does not exist, the corresponding position outputs -1.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3, -1]
Explanation:
    For the number 4 in num1, you cannot The next larger number is found in the array, so -1 is output.
    For the number 1 in num1, the next larger number to the right of the number 1 in the second array is 3.
    For the number 2 in num1, there is no next larger number in the second array, so -1 is output.


Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3, -1]
Explanation:
    For the number 2 in num1, the next larger number in the second array Yes 3.
    For the number 4 in num1, there is no next larger number in the second array, so -1 is output.


note:

All elements in nums1 and nums2 are unique.
The array size of nums1 and nums2 does not exceed 1000.

Source: LeetCode (LeetCode)
link: https://leetcode-cn.com/problems/next-greater-element-i
Copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

Idea 1: Directly follow the logic, first find whether there is a corresponding number in num2, if there is, then find the value greater than itself after it, otherwise it is -1

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        ans = []
        length = len(nums2)
        for n1 in nums1:
            if n1 not in nums2:
                ans.append(-1)
            else:
                t = nums2.index(n1)
                f = 0
                for i in range(t + 1, length):
                    if nums2[i] > n1:
                        ans.append(nums2[i])
                        f = 1
                        break
                if f == 0:
                    ans.append(-1)
        return ans

Idea 2:

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        ans = []
        stack = [] 
        dict1 = {}
        for n in nums2:
            if stack !=[] and n > stack[-1]:
                while stack != [] and n > stack[-1]:
                    dict1[stack[-1]] = n
                    stack.pop()
            stack.append(n)         

        for n in nums1:
            if n in dict1:
                ans.append(dict1[n])
            else:
                ans.append(-1)
        return ans

 

Published 314 original articles · 22 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_39451578/article/details/105090916