496. 下一个更大的元素I

链接

https://leetcode.cn/problems/next-greater-element-i/description/

思路

1. 暴力解法

  暴力解法没啥好说的,对于nums1中的元素,先找到其在nums2中的位置,然后往后找比他大的第1个元素就好了。这样的做法是O(m*n)的时间复杂度。

2. 单调栈

  单调栈,顾名思义,就是在栈内,元素要么是单调递减的,要么是单调递增的。

  这个题目要求我们找下一个更大的元素,所以这个栈应当是递减的。(即栈顶元素最小)而我们要找的是下一个更大的元素,所以要从后往前遍历nums2。

  单调栈也有2种做法,第1个是在线处理,我们在不断的生成单调栈的同时,去判断是否命中nums1,命中则加入到res中。

  第2个是一次处理完nums2,将每个元素对应的下一个更大的元素映射成一个k-v对,存储在一个dict中。然后遍历nums1,根据dict生成最后的res。

代码-单调栈-在线处理

class Solution:
    def nextGreaterElement(self, nums1, nums2):
        single_stack = []
        res = [-1 for i in range(len(nums1))]
        mem1 = dict()
        for i, v in enumerate(nums1):
            mem1[v] = i
        for i in nums2[::-1]:
            if single_stack.__len__() == 0:
                single_stack.append(i)
            else:
                while single_stack.__len__() > 0:
                    top_val = single_stack[-1]
                    if top_val > i:
                        if i in mem1:
                            idx = mem1[i]
                            res[idx] = top_val
                        break
                    else:
                        single_stack.pop()
                single_stack.append(i)
        return res

 

代码-单调栈-生成所有

class Solution:
    def nextGreaterElement(self, nums1, nums2):
        single_stack = []
        mem = dict()
        for i in nums2[::-1]:
            while single_stack.__len__() > 0:
                top_val = single_stack[-1]
                if top_val > i:
                    break
                else:
                    single_stack.pop()
            if len(single_stack) == 0:
                mem[i] = -1
            else:
                mem[i] = single_stack[-1]
            single_stack.append(i)
        res = [mem[i] for i in nums1]
        return res

 

三刷-来个简单点的代码

class Solution:
    def nextGreaterElement(self, nums1, nums2):
        mem = dict()
        res = [-1 for i in nums1]
        single_stack = []
        for i, v in enumerate(nums1):
            mem[v] = i
        for i in range(len(nums2)-1, -1, -1):
            while single_stack and single_stack[-1] < nums2[i]:
                single_stack.pop()
            if single_stack and nums2[i] in mem:
                res[mem[nums2[i]]] = single_stack[-1]
            single_stack.append(nums2[i])
        return res

 

posted @ 2023-10-07 13:27  BJFU-VTH  阅读(6)  评论(0编辑  收藏  举报