March——496. The next bigger element I, II (monotonic stack)

 

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        #暴力解法
        res = []
        for  i in range(len(nums1)):
            index = nums2.index(nums1[i])
            flag = False
            while index<len(nums2):
                if nums2[index]>nums1[i]:
                    flag = True
                    break
                index+=1
            if flag:
                res.append(nums2[index])
            else:
                res.append(-1)
        
        return res



        #单调栈
        stack = []
        dic = dict()
        #这样做使得num2中每个元素如果存在下一个比他大的元素,那么就会形成键值对。
        #然后让nums1中的元素去查找它,如果找到了就返回该值,如果找不到那就返回-1
        for num in nums2:
            while stack and stack[-1]<num:
                dic[stack.pop()] = num
            stack.append(num)

        return [dic.get(num,-1) for num in nums1]
  • Violent law is easier to think about, but it is not very efficient
  • The monotonic stack is used to form a hash table, the key-value pairs are all increasing, and then num1 performs a lookup operation in the hahs table
  • The method of monotonous stack is never expected, but the efficiency is higher

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        
        n = len(nums)
        #ret放的是最终结果
        ret = [-1] * n
        #栈放得是索引
        stk = []

        for i in range(n * 2):
            while stk and nums[stk[-1]] < nums[i % n]:
                ret[stk.pop()] = nums[i % n]
            stk.append(i % n)

        return ret

  •  Since it is a circular array, just straighten the array, that is, append an array after the original array
  •  What is stored in the stack is not a value and a subscript of a list
  •  Because it is straightened, the flower of the current element must be modulo n

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/114437741