496. The next largest element python implementation

496. The next bigger element 1

"Stay hungry stay young "
is described in LeetCode. This is also a simple question. According to a certain element, find the element in the list that is closest to it and larger than it. Under normal circumstances, it can be solved by violence , But when there is too much data, only other methods can be adopted. For such problems, there is a more classic method to solve this problem, which is to use a monotonic stack data structure, which is still the idea of ​​"**using space for time"**:

Monotonic stack:

In essence, it still satisfies the last-in-first-out nature of the stack, but it must always maintain a monotonic sequence from the top of the stack to the bottom of the stack. Once there is a non-monotonous part, the stack is popped. The stack itself changes dynamically.

The idea of ​​this question:

For this question, first we consider building a hash table, corresponding to the data structure of the dictionary in python, each element corresponds to the next element larger than it in num2, if not, return -1, based on this operation , The problem is transformed into the problem of how to create a dic. Here, a monotonic stack is used .
When an element is put on the stack, a judgment is first made on the elements in the stack:

  • If the current element is larger than the top element of the stack, then the top element of the stack is popped from the stack and a mapping is established between the top element of the stack and the current element
  • If the element on the top of the stack is larger than the element that you want to push, or the stack is empty, push the element to the stack

Based on the above description, the code is as follows:

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

Complexity analysis:

Time complexity : O(M+N) where M and N are the lengths of the arrays nums1 and nums2, respectively.
Space complexity : O(N) When we traverse nums2, we need to use the stack and hash map to temporarily store the answer.

Guess you like

Origin blog.csdn.net/weixin_45717055/article/details/112975104